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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With