Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values out of a JArray in JSON.net

Tags:

c#

json.net

I am having trouble getting data from my JArray, specifically I am trying to access the ID value. Here is a JSON example

{
"page": 1,
"totalPages": 5,
"pageSize": 2,
"sortField": "label",
"sortOrder": "asc",
"content": [
  {
  "organizationId": "Org123",
  "id": "333",
  "label": "comp1"
  },
  {
  "organizationId": "Org123",
  "id": "444",
  "label": "comp2"
  }
]
}

And here is what I have in C#

        JArray jArray = new JArray(jsonString);

        foreach (JValue item in jArray)
        {
            Console.WriteLine(item["id"]);
        } 

I know I need to check the JValue to make sure it is an ID type, but I am confused on object types assigned once it's broken down in the JArray.

like image 580
ngc Avatar asked Jul 28 '15 14:07

ngc


1 Answers

First off, you're dealing with an object at the top level. After parsing the object, you need to look at the content array:

var obj = JObject.Parse(json);
    
foreach (JObject element in obj["content"])
{
    Console.WriteLine(element["id"]);
}

Here's an example: https://dotnetfiddle.net/DhVZFf

Also (and this might just be a typo), your JSON is malformed. Specifically, the comma separating elements in the content array are in the wrong place:

{
    "organizationId": "Org123",
    "id": "333",
    "label": "comp1", // <---
}
{
  "organizationId": "Org123",
  "id": "444",
  "label": "comp2",
}

Those commas should be between array elements:

{
    "organizationId": "Org123",
    "id": "333",
    "label": "comp1"
}, // <---
{
  "organizationId": "Org123",
  "id": "444",
  "label": "comp2"
}

Here are other usefull examples https://www.newtonsoft.com/json/help/html/queryinglinqtojson.htm

like image 160
Andrew Whitaker Avatar answered Oct 17 '22 01:10

Andrew Whitaker