Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialised class is blank - JSON C#

I'm deserialising a JSON API response into a class - but the class is empty after the code has run, i.e. doesn't appear to have deserialised at all.

Here is an example of the JSON, called responsetext:

{"ON":{"Date":"3/16/2017 10:12:51 AM","PARAM1":"84","PARAM2":"31597.535"},"OFF":{"Date":"3/16/2017 9:05:53 AM","PARAM3":"0","PARAM4":"0"}}

I have two classes:

public class ON
{
public Date {get; set;}
public string PARAM1 {get; set;}
public string PARAM2 {get; set;}
}
public class OFF
{
public Date {get; set;}
public string PARAM3 {get; set;}
public string PARAM4 {get; set;}
}

And I deserialise here:

ON class1 = JsonConvert.DeserializeObject<ON>(responsetext);
OFF class2 = JsonConvert.DeserializeObject<OFF>(responsetext);

But the classes are empty. What am I doing wrong?

like image 486
reviloSlater Avatar asked Jun 01 '26 22:06

reviloSlater


2 Answers

You're trying to deserialise the same JSON into two different classes, as if the deserialiser will magically know which part of the JSON to use. You need a wrapping class:

public class Message
{
    public ON ON { get; set; }

    public OFF OFF { get; set; }
}

And then deserialise like this:

var message = JsonConvert.DeserializeObject<Message>(responsetext);

Now you can access both message.ON and message.OFF:

screenshot of running example

like image 77
user247702 Avatar answered Jun 04 '26 22:06

user247702


What you have in your response is not a single instance of On or Off, but an object containing one of each. When you tell JsonConvert to deserialize this wrapper into one or the other class, it instantiates a copy of the class, then looks at the JSON string for properties to set, but doesn't find any because the containing object is neither an On nor an Off and doesn't have any fields of either. So, it just gives you back the empty object.

You need a third class that contains an ON instance and an OFF instance, and deserialize to that type; then you'll get the results you want. Or, you can do a little parsing yourself to extract the JSON for each object into separate strings, then deserialize them (but that's kind of defeating the purpose of using Newtonsoft.JSON in the first place).

like image 24
KeithS Avatar answered Jun 04 '26 23:06

KeithS