首页 > 解决方案 > 如何在 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?谢谢你。

标签: c#jsonlinqjson.net

解决方案


我假设您的示例代码使用 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());
    }
}

推荐阅读