首页 > 解决方案 > 迭代思想 JSON 对象并获取特定属性

问题描述

我无法正确迭代我得到的 json 响应。没有特定的 id/key 来循环它们。

首先是我的示例 json 对象。json 的键是 id 并且是动态的。

示例 JSON

{
"1": {
    "docid": "26",
    "title": "QT1030-3 Product Development Plan Template",
    "category": "Template/Form",
    "children": {}
},
"2": {
    "docid": "27",
    "title": "QT1030-2 Product Requirements Template",
    "category": "Template/Form",
    "children": {}
},
"3": {
    "docid": "28",
    "title": "QT1030-1 Product Specifications Template",
    "category": "Template/Form",
    "children": {}
},
"60": {
    "docid": "22",
    "title": "QT1030-7 Design & Development Review Template",
    "category": "Template/Form",
    "children": {}
},
"61": {
    "docid": "23",
    "title": "QT1030-6 Design Inputs Outputs Matrix",
    "category": "Template/Form",
    "children": {}
},
"63": {
    "docid": "24",
    "title": "QT1030-5 DHF Index Template",
    "category": "Template/Form",
    "children": {}
},
"82": {
    "docid": "25",
    "title": "QT1030-4 Material Specifications",
    "category": "Template/Form",
    "children": {}
}

在这里,我尝试循环动态但不确定如何正确迭代。我尝试了类似 item.docid 但没有成功。

C# 代码

C# 代码

if (response.IsSuccessStatusCode)
{
    var documents = await response.Content.ReadAsStringAsync();
    dynamic nodelist = JsonConvert.DeserializeObject(documents);

    foreach (var item in nodelist)
    {
        int i = 0;
    }
}

标签: c#json

解决方案


你快到了,你可以迭代它并获得docid如下值:

dynamic nodeList= JsonConvert.DeserializeObject(documents);

foreach (JProperty node in nodeList)
{
    Console.WriteLine(node.Value["docid"]);
}

推荐阅读