0

i'm trying to cast a simple json string to my class

Json string

{"Title":"SQL","Connection":"","Command":"select * from tbl_roles"}

Class

public class EmailMessage
    {
        [JsonProperty("Title")]
        public string Title { get; set; }
        [JsonProperty("Connection")]
        public string Connection { get; set; }
        [JsonProperty("Command")]
        public string Command { get; set; }
    }

C# Code

    EmailMessage emailMessage = JsonConvert.DeserializeObject(email.BodyText.Text.Replace("\r",string.Empty).Replace("\n",string.Empty)) as EmailMessage;
                

the variable returning null

the image of the watch of the Command

JsonConvert.DeserializeObject(email.BodyText.Text.Replace("\r",string.Empty).Replace("\n",string.Empty))

Watch

15
  • 2
    The result of JsonConver.DeserializeObject is a plain object. And you cannot simply cast an object to EmailMessage, thus somobject as EmailMessage returns null. Use JsonConvert.DeserializeObject<EmailMessage>(...) instead Commented Jan 2, 2022 at 12:44
  • I hope you aren't writing software that accepts SQL commands by email, that sounds like a recipe for a major SQL injection disaster.... Commented Jan 2, 2022 at 12:47
  • yes it is run sql via email and also return json object of the result Commented Jan 2, 2022 at 12:53
  • @MaherKhalil You understand the security implications of that? So literally everyone can send literally any query to your service via email and it's just executed? Commented Jan 2, 2022 at 13:40
  • Can you please show the result of this - json = email.BodyText.Text.Replace("\r",string.Empty).Replace("\n",string.Empty)) Commented Jan 2, 2022 at 13:44

2 Answers 2

1

You create a variable for available JSON.

string jsonBody = //Prepare available json string here...

And use this code:

EmailMessage emailMessage = JsonConvert.DeserializeObject<EmailMessage>(jsonBody);
Sign up to request clarification or add additional context in comments.

Comments

0

The result of JsonConver.DeserializeObject is a plain object. Well -- in your case -- it's a JObject actually, cast to an object. And you cannot simply cast an object (or JObject) to EmailMessage, thus somobject as EmailMessage returns null. Because that's how the as operator is defined.

Use

JsonConvert.DeserializeObject<EmailMessage>(...) 

instead. It will return an instance of the generic type parameter, or throw an exception, if the JSON string cannot be parsed to that type (or the JSON string is invalid in the first place)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.