简体   繁体   中英

Getting nested data out of JSON in C#

I have some JSON with Two objects and these each have 3 objects nested.

{ "FirstPerson": { "number": "101", "a10": "1001", "a20": "1002" }, "SecondPerson": { "number": "102", "a10": "2001", "a20": "2001" } }

In c# asp.net mvc2 I've been able to get to "FirstPerson" or "SecondPerson" using a Hashtable but how do I get to "number" or "a10" when I know "FirstPerson"?

eg an objects inside an object.

Is a Hashtable the best use for this or should I be using something else?

Thanks in advance.

I found that solution for your problem may be give a clue to solve that

Want to convert a C# object into it's JSON equivalent? Here is a simple object from the System.Web.Script namespace that does exactly that:

System.Web.Script.Serialization.JavaScriptSerializer . It is stored in the System.Web.Extentions DLL (.Net Framework 3.5 only)

Using this object we serialize and deserialize objects in C#. Here is a quick sample:

A simple Employee object:

public class Employee
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string ID { get; set; }   
}

Adding some instances of them to a List:

Employee oEmployee1 =

   new Employee{Name="Pini",ID="111", Age="30"};

Employee oEmployee2 =

  new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };

Employee oEmployee3 =

    new Employee { Name = "Yoni", ID = "Biton", Age = "20" };

List oList = new List()

{ oEmployee1, oEmployee2, oEmployee3 };

Serializing then:

System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); string sJSON = oSerializer.Serialize(oList);

And here is the output:

[{"Name":"Pini","Age":"30","ID":"111"},

{"Name":"Yaniv","Age":"31","ID":"Cohen"},

{"Name":"Yoni","Age":"20","ID":"Biton"}]

For your consideration here is the link http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx

I have had good results using JsonConvert. It seems to do a good job of knowing what to do with collections. Just define the class you want to de-serialize to and have at it.

http://james.newtonking.com/projects/json-net.aspx

Example:

MyCollection col = JsonConvert.DeserializeObject<MyCollection>(this.HttpContext.Request.Params[0]);

Where MyCollection is a class which contains a collection of, in your case, people.

You could assign the JSON object to a dynamic variable and access the properties that way (only in C# 4.0 though)

dynamic jsonData = jsonObject;
int workflowNum = jsonData.SecondPerson[0].workflow;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM