簡體   English   中英

使用Newtonsoft在C#中迭代嵌套的JSON數組

[英]Iterating through a nested JSON Array in C# with Newtonsoft

我有一塊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);
}

這不起作用,但我希望它說明了我的最終目標。 我一直無法拼湊如何實現這一目標。

JObject是一個對象(類似於一個類):

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

JArray是一個JSON數組,包含多個JObject實體:

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

JSON文檔的根可以是對象或數組。 在你的情況下,它是一個數組。

下面的代碼和提示顯示您的代碼很好,只要您將文檔反序列化為數組即可。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM