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?
}
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
Dotnet Fiddle program
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