Search code examples
c#jsonjson.netdeserializationjson-deserialization

Trying to deserialize JSON returns null values


Using the method JsonConvert.DeserializeObject returns the default values for all properties.

var current = JsonConvert.DeserializeObject<Current>(myJson);
{
    "location": {
        "name": "London"
    },
    "current": {
        "temp_c": 5.0,
        "cloud": 50
    }
}
public class Current
{
    public double Temp_c { get; set; }
    public double Cloud { get; set; }
}

The expected current object should have the values: 50 for Cloud, and 5.0 for Temp_c, but returns the default values for all properties.


Solution

  • You need to define a class model like json object and then deserialize to it

    public class YourModel {
    
       //create location class that has Name property
       public Location Location { get; set; }
    
       //create current class that has Temp_c and Cloud property
       public Current Current { get; set; }
    
    }
    

    and then

    var data = JsonConvert.DeserializeObject<YourModel>(myJson);
    

    and get the current value from data object

    var current = data.Current;