如何在 C# 中访问 JSON 中的数组项

How to access item in array in JSON in C#

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());
    }
}