How to parse nested JSON data structure

两盒软妹~` 提交于 2019-12-04 11:30:33

From the top-level JToken, you can use SelectToken() to navigate to the JArray that has the data you are interested in:

JToken token = JToken.Parse(json);
JArray men = (JArray)token.SelectToken("people[0].men");

From there you can process the JArray as you normally would:

foreach (JToken m in men)
{
    Console.WriteLine("id: " + m["id"]);
    Console.WriteLine("name: " + m["name"]);
    Console.WriteLine("age: " + m["age"]);
    Console.WriteLine();
}

Same thing for the women array, except the SelectToken() path would be people[1].women.

DEMO: https://dotnetfiddle.net/7BoiUO

Use the http://json2csharp.com/ It generates the classes. I can't copy it, because you put here as a picture, not text. For the array you have to create other class. In your case you will have a People class that contains Men[] and Women[] arrays. The Men and Women classes contain an another array, which contains the Id, Name, Age. I develop a similar app, and I use the Newtonsoft Json. It works perfectly with the arrays as well.

Ritesh Khichadia

Use Json.net

You can add it via nuget. Here's a good guide to nested json parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!