遍历JObject嵌套数组 [英] Looping through JObject nested array

查看:891
本文介绍了遍历JObject嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法确切地知道如何通过此JObject来获取运行时的id属性.

I can not figure out exactly how to did through this JObject in order to retrieve the id property under runs.

我有以下代码,可以成功为我提供条目下的id属性,但是如何再次嵌套它以进入运行部分并获得这些ID?

I have this following code which will successfully give me the id property that is under entries, but how can I nest this again to go into the runs sections and get those ID's?

JSON:

{
  "id": 168,
  "name": "section 1",
  "entries": [
    {
      "id": "908-9876-908",
      "suite_id": 15,
      "name": "List 1",
      "runs": [
        {
          "id": 169,
          "suite_id": 15
        }
      ]
    },
    {
      "id": "998-4344-439",
      "suite_id": 16,
      "name": "List 2",
      "runs": [
        {
          "id": 170,
          "suite_id": 16
        }
      ]
    }
  ]
}

C#代码:

JObject obj = JsonConvert.DeserializeObject<JObject>(response);

foreach (JObject id in obj["entries"])
{
    string returnable = (string)id["id"];
    Console.WriteLine(returnable);
}

我尝试查看["entries"] ["runs"],但那也没有用.

I have tried looking at ["entries"]["runs"] but that also was not working.

打印出来的是:

908-9876-908
998-4344-439

我想要的是

169
170

推荐答案

您可以使用以下代码实现

You can achieve it using the following code

var jsonObject = JObject.Parse(json);

foreach (var entry in jsonObject["entries"])
{
    foreach (var run in entry["runs"])
    {
        string returnable = (string)run["id"];
        Console.WriteLine(returnable);
    }               
}

您想看

169
170

它们是runs数组中的id值,因此应在内部循环中枚举它们.您还错过了"name": "section 1"

They are an id values from runs array, therefore you should enumerate them in the inner loop. You've also missed a comma after "name": "section 1"

这篇关于遍历JObject嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆