Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

c# - How to parse nested JSON data structure

In a Windows Phone app I need to parse JSON data. I am able to get the values for keys which aren't nested. But if the JSON has arrays inside arrays, then how do I extract values from the JSON file?

In the past what I did was parse the JSON into a JArray object, then from the JToken I got the value of a specified string key.

In the JSON below, people has men and women, and men itself has many men with different IDs. So if I have this complete thing as a JSON string, how do I print the value of the ID of a particular man? I could have converted into JArray and access indexed values if there were no nested arrays here, but how to do it now?

Here is my JSON:

{
    "people": [
        {
            "men": [
                {
                    "id": 0,
                    "name": "alex",
                    "age": 25
                },
                {
                    "id": 1,
                    "name": "bob",
                    "age": 26
                },
                {
                    "id": 2,
                    "name": "charlie",
                    "age": 27
                }
            ]
        },
        {
            "women": [
                {
                    "id": 0,
                    "name": "alexys",
                    "age": 25
                },
                {
                    "id": 1,
                    "name": "bethany",
                    "age": 26
                },
                {
                    "id": 2,
                    "name": "catherine",
                    "age": 27
                }
            ]
        }
    ]
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...