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"
}
]
}"
我使用这段代码,不能打印出"content"的值(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());
}
}