使用Newtonsoft在C#中迭代嵌套的JSON数组

时间:2017-11-22 01:28:01

标签: c# json json.net

我有一个JSON块,如下所示:

[
  {
    "id": 1,
    "name": "Section1",
    "project_id": 100,
    "configs": [
      {
        "id": 1000,
        "name": "myItem1",
        "group_id": 1
      }
    ]
  },
  {
    "id": 2,
    "name": "Section2",
    "project_id": 100,
    "configs": [
      {
        "id": 1001,
        "name": "myItem2",
        "group_id": 2
      },
      {
        "id": 1002,
        "name": "myItem3",
        "group_id": 2
      },
      {
        "id": 1003,
        "name": "myItem4",
        "group_id": 2
      }
    ]
  },
  {
    "id": 3,
    "name": "Section3",
    "project_id": 100,
    "configs": [
      {
        "id": 1004,
        "name": "myItem5",
        "group_id": 5
      },
    ]
  }
]

我把它作为JArray把它拉进了Memory。

我需要迭代这一点,以便我只从配置子数组中获取id列表。理想情况下,我最终会得到这样的结果:

1000, myItem1
1001, myItem2
1002, myItem3
1003, myItem4
1004, myItem5

我很难理解Newstonsoft称之为JObject与JArray的对象,或者如何访问每个数据结构的各个部分。我现在的情况如下:

foreach (JObject config in result["configs"])
{
    string id = (string)config["id"];
    string name = (string)config["name"];
    string gid = (string)config["group_id"];

    Console.WriteLine(name + " - " + id + " - " + gid);
}

这不起作用,但我希望它说明了我的最终目标。我一直无法拼凑如何实现这一目标。

1 个答案:

答案 0 :(得分:7)

JObject是一个对象(类似于一个类):

{
    "a": 1,
    "b": true
}

JArray是一个JSON数组,包含多个JObject个实体:

[
    {
        "a": 1,
        "b": true
    },
    {
        "a": 2,
        "b": true
    }
]

JSON文档的根可以是对象或数组。在你的情况下,它是一个数组。

以下代码和fiddle表明您的代码没问题,只要您将文档反序列化为数组即可。

string json = "[{\"id\":1,\"name\":\"Section1\",\"project_id\":100,\"configs\":[{\"id\":1000,\"name\":\"myItem1\",\"group_id\":1}]},{\"id\":2,\"name\":\"Section2\",\"project_id\":100,\"configs\":[{\"id\":1001,\"name\":\"myItem2\",\"group_id\":2},{\"id\":1002,\"name\":\"myItem3\",\"group_id\":2},{\"id\":1003,\"name\":\"myItem4\",\"group_id\":2}]},{\"id\":3,\"name\":\"Section3\",\"project_id\":100,\"configs\":[{\"id\":1004,\"name\":\"myItem5\",\"group_id\":5},]}]";
JArray obj = Newtonsoft.Json.JsonConvert.DeserializeObject<JArray>(json);
foreach (var result in obj)
{
    foreach (JObject config in result["configs"])
    {
        string id = (string)config["id"];
        string name = (string)config["name"];
        string gid = (string)config["group_id"];

        Console.WriteLine(name + " - " + id + " - " + gid);
    }
}