c# - 如何在 C# 中以 JSON 格式访问数组中的项目
问题描述
string json = "{"httpStatusCode": "OK",
"count": 10,
"entities": [
{
"responseCode": 200,
"ResponseCode": 0,
"headers": null,
"Headers": null,
"content": "name1"
},
{
"responseCode": 200,
"ResponseCode": 0,
"headers": null,
"Headers": null,
"content": "name2"
}
]
}"
我使用这段代码并不能打印出“内容”(name1,name2)的值,它只会跳过if语句
JObject o = JObject.Parse(json);
foreach (var element in o["entities"])
{
foreach(var ob in element)
{
if(ob.toString() == "content")
Console.WriteLine(ob);
}
}
那么,如何打印出 name1 和 name2?谢谢你。
解决方案
我假设您的示例代码使用 Newtonsoft.Json 库。
对您的代码进行一些修改实际上可以使您的代码正常工作。您需要在 JSON 中搜索名为“content”的属性。为此,将您的类型JToken
转换为JProperty
类型。然后您可以像这样访问它的名称和值:
JObject o = JObject.Parse(json);
foreach (var element in o["entities"])
{
foreach (var ob in element)
{
if (ob is JProperty prop && prop.Name == "content")
Console.WriteLine(prop.Value.ToString());
}
}
推荐阅读
- css - 如何在 Css 中创建菱形(虚线)边框底部
- php - 如何在没有 Ajax 的情况下将 PHP 文件连接到 HTML 文件
- c++ - 线程中的 QModbus 在 Qt 中产生错误
- maven - 使用 --base-href 构建 Angular 库
- python - Python 正则表达式表示第二个最后一个单词
- python - 继续接收 FileNotFoundError: [Errno 2] No such file or directory: '' 在 python 中写入文件时出错
- python - 如何使用索引号遍历 python 列表?
- javascript - 在没有明确条件```while(y)```的情况下没有得到循环
- pagination - 如何使用带有 Pageable 的 Spring Data JPA 分页来更改数据?
- typescript - 我可以在 Typescript 方法装饰器中访问目标类实例吗?