How to parse nested JSON data structure(如何解析嵌套的 JSON 数据结构)
问题描述
在 Windows Phone 应用程序中,我需要解析 JSON 数据.我能够获取未嵌套的键的值.但是如果 JSON 数组里面有数组,那我该如何从 JSON 文件中提取值呢?
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?
过去我所做的是将 JSON 解析为 JArray 对象,然后从 JToken 中获取指定字符串键的值.
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.
在下面的JSON中,people
有men
和women
,而men
本身有很多不同的男人身份证.因此,如果我将这个完整的东西作为 JSON 字符串,我如何打印特定人的 ID 值?如果这里没有嵌套数组,我可以转换成 JArray 并访问索引值,但是现在该怎么做呢?
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?
这是我的 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
}
]
}
]
}
推荐答案
从顶层JToken
,可以使用SelectToken()
导航到JArray
有你感兴趣的数据:
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");
从那里您可以像往常一样处理 JArray
:
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();
}
对于 women 数组也是一样,除了 SelectToken()
路径是 people[1].women
.
Same thing for the women array, except the SelectToken()
path would be people[1].women
.
演示: https://dotnetfiddle.net/7BoiUO
这篇关于如何解析嵌套的 JSON 数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何解析嵌套的 JSON 数据结构
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01