Reputation: 22984
How to iterate through pure JSON Array like the following, in C# Newtonsoft?
[
78293270,
847744,
32816430
]
or,
["aa", "bb", "cc"]
All the existing answers that I found on SO are in KeyValuePair format, not this pure JSON Array format. Thx.
JArray array = JsonConvert.DeserializeObject<JArray>(json);
foreach(JObject item in array)
{
// now what?
}
Upvotes: 5
Views: 3020
Reputation: 10839
Parse the string using static Parse
method of JArray
. This method returns a JArray from a string that contains JSON. Please read it about here.
var jArray = JArray.Parse(arrStr);
foreach (var obj in jArray)
{
Console.WriteLine(obj);
}
A simple program for your inputs which you can run to validate at dotnetfiddle.
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
var arrStr = "[78293270, 847744, 32816430]";
var jArray = JArray.Parse(arrStr);
foreach (var obj in jArray)
{
Console.WriteLine(obj);
}
var aStr = "[\"aa\", \"bb\", \"cc\"]";
var jArray1 = JArray.Parse(aStr);
foreach (var obj in jArray1)
{
Console.WriteLine(obj);
}
}
}
The output of above code is
78293270
847744
32816430
aa
bb
cc
Upvotes: 3
Reputation: 2026
Do you mean "how to get values from iterated JObject
?
foreach(var item in array) // var is JToken, can be cast to JObject
{
int number = item.Value<int>();
Console.WriteLine(number);
}
Upvotes: 0