Learn how to retrieve data from a JSON array in .NET C# using the Newtonsoft.Json library. Easily access and iterate through nested data.
To get data from a JSON array inside a JSON object in C#, you can use the Newtonsoft.Json library (also known as Json.NET) and the JObject and JArray classes.
Assuming you have a JSON object with a property “myArray” that contains an array of objects, you can retrieve the array like this:
string jsonString = "{\"myArray\":[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Jane\"}]}";
JObject jsonObj = JObject.Parse(jsonString);
JArray myArray = (JArray)jsonObj["myArray"];
You can then loop through the items in the array and access their properties like this:
foreach (JObject item in myArray)
{
int id = (int)item["id"];
string name = (string)item["name"];
// do something with id and name
}
If the JSON array only contains primitive values (i.e., strings, numbers, booleans, etc.) and not nested objects, you can retrieve the values using the JArray class from the Newtonsoft.Json library in C#.
Assuming you have a JSON string that contains an array of numbers, you can retrieve the array like this:
string jsonString = "[1, 2, 3, 4, 5]";
JArray jsonArray = JArray.Parse(jsonString);
You can then loop through the items in the array and access their values like this:
foreach (int number in jsonArray)
{
// do something with the number
}
Alternatively, you can convert the JArray to a C# array or List using the ToArray() or ToList() methods like this:
int[] numbers = jsonArray.ToObject<int[]>();
List<int> numberList = jsonArray.ToObject<List<int>>();
Note that you will need to handle any errors or missing properties if they occur.