skip to Main Content

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.

2

Answers


  1. 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;
    
    Login or Signup to reply.
  2. your ‘Current’ class is far of been like the JSON you post.

    You need to convert the JSON string to a C# class. You can use QuickType to convert it (Newtonsoft compatible).

    Note: I am using System.Text.Json.Serialization but the class model should be equal, just change:

    [JsonPropertyName("temp_c")] // .Net serializer (I prefer this)
    

    to

    [JsonProperty("temp_c")] // Newtonsoft.Json serializer
    

    (replace "temp_c" for every name)

    Here is the class model (a complete console application) you need:

    using System;
    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    #nullable disable
    
    namespace test
    {
        public class Weather
        {
            [JsonPropertyName("location")]
            public Location Location { get; set; }
    
            [JsonPropertyName("current")]
            public Current Current { get; set; }
        }
    
        public class Location
        {
            [JsonPropertyName("name")]
            public string Name { get; set; }
        }
    
        public class Current
        {
            [JsonPropertyName("temp_c")]
            public double TempC { get; set; }
    
            [JsonPropertyName("cloud")]
            public int Cloud { get; set; }
        }
    
    
        class Program
        {
            static void Main(string[] args)
            {
                string json = "{"location": { "name": "London" }, "current": { "temp_c": 5.0, "cloud": 50 }}";
                Weather myWeather = JsonSerializer.Deserialize<Weather>(json);
    
                Console.WriteLine("Location: {0} - Temp: {1:F}", myWeather.Location.Name, myWeather.Current.TempC);
            }
        }
    }
    

    Now the Deserializer will work OK.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search