Home > Back-end >  JsonConvert.DeserializeObject return null when cast to class
JsonConvert.DeserializeObject return null when cast to class

Time:01-03

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

CodePudding user response:

You create a variable for available JSON.

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

And use this code:

EmailMessage emailMessage = JsonConvert.DeserializeObject<EmailMessage>(jsonBody);

CodePudding user response:

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)

  • Related