Getting Values ​​from JArray to JSON.net

I'm having trouble getting data from my JArray, in particular, I'm trying to access the value of an identifier. 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 this is what I have in C #

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

I know that I need to check JValue to make sure it is an identifier type, but I am confused with the types of objects assigned after it is split into a JArray.

+5
source share
1 answer

Firstly, you are 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 it could just be a typo), your JSON is incorrect. In particular, 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", } 

These commas should be between the elements of the array:

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

All Articles