Gabriel Yap
Gabriel Yap

Reputation: 5

Iterate thought JSON object and get specific properties

I'm having trouble to properly iterate with the json response i got. There's no specific id/key to loop them.

First here is my sample json object. The key's of json is id and is dynamic.

Sample 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": {}
}

Here i tried to loop dynamic but not sure how to iterate properly. I tried something like item.docid but no success.

C# code

C# Code

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

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

Upvotes: 0

Views: 185

Answers (1)

Selim Yildiz
Selim Yildiz

Reputation: 5370

You are almost there, you can iterate it and get value of docid as follow:

dynamic nodeList= JsonConvert.DeserializeObject(documents);

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

Upvotes: 1

Related Questions