Home > Net >  How to Deserialize Json Newtonsoft
How to Deserialize Json Newtonsoft

Time:10-07

I had this JSON string from server previously

"[
 {
    \"name":\"XYZ",
    \"age\":\"75\",
    \"height\":\"170.1\",
    \"weight\":\"69.6\",
    \"dob\":\"2000-10-07T07:23:26.876Z\"
 },
 {
    \"name":\"ABC",
    \"age\":\"15\",
    \"height\":\"160.1\",
    \"weight\":\"55.6\",
    \"dob\":\"1990-10-07T07:23:26.876Z\"
 },
]"

for which I used a class like this

   public class Person
   {
      [JsonProperty("name")]
      public string Name {get; set;}
      [JsonProperty("age")]
      public decimal Age {get; set;}
      [JsonProperty("height")]
      public decimal Height {get; set;}
      [JsonProperty("weight")]
      public decimal Weight {get; set;}
      [JsonProperty("dob")]
      public DateTime DOB {get; set;}   
   }

and I've deserialized it using

    JsonConvert.DeserializeObject<Person[]>(jsonString)

But now the server changed the JSON to be like this

"{
    \"XYZ":
    {
        \"age\":\"75\",
        \"height\":\"170.1\",
        \"weight\":\"69.6\",
        \"DOB\":\"2000-10-07T07:23:26.876Z\"
    },
    \"ABC":
    {
        \"age\":\"15\",
        \"height\":\"160.1\",
        \"weight\":\"55.6\",
        \"DOB\":\"1990-10-07T07:23:26.876Z\"
    }
}"

The name property was removed and instead it became the root element. I tried changing the class to be like this but it's not working. How do I deserialize it?

    public class PersonResult
    {
        public Person [] Persons {get; set;}
    }

CodePudding user response:

string jsonString = @"{
    ""XYZ"":
    {
        ""age"":""75"",
        ""height"":""170.1"",
        ""weight"":""69.6"",
        ""DOB"":""2000-10-07T07:23:26.876Z""
    },
    ""ABC"":
    {
        ""age"":""15"",
        ""height"":""160.1"",
        ""weight"":""55.6"",
        ""DOB"":""1990-10-07T07:23:26.876Z""
    }
}";

// deserialize
var data = JsonConvert.DeserializeObject<Dictionary<string, Person>>(jsonString);
// fixup
foreach (var (key, value) in data)
{
    value.Name = key;
}
// display
foreach (var (key, value) in data)
{
    Console.WriteLine($"{value.Name}, {value.Age}");
}
  • Related