Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
Hi, can somebody help with the proper way to deserialize json data of this format:

[{person:{name:"James", age:26}}, {person:{name:"Mary", age:36}}, {person:{name:"Kofi", age:46}}]


The code i'am using is as below:

C#
WebRequest request = WebRequest.Create("url");
WebResponse response = request.GetResponse();

string json;

using (var sr = new StreamReader(response.GetResponseStream()))
{
    json = sr.ReadToEnd();
}


var serializer = new JavaScriptSerializer();

var persons= serializer.Deserialize<List<auto>>(json);

foreach (var item in persons)
{
    Console.Write("name:" + item.name + " and age: " + item.age);
}


the class I'am mapping to is as below:

C#
public class person
{
  public string name{get;set;}
  public int age{get; set;}
}


I keep getting nulls and empty strings for the name and age properties when I run this code. I will appreciate it a lot if someone can help me out.
Posted

I had to make call item.person.name and item.person.age in the foreach loop and make sure all properties in the person class were of type string.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900