Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Array Iteratiion in C# Newtonsoft

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?
}
like image 627
xpt Avatar asked Oct 17 '22 19:10

xpt


1 Answers

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

like image 137
user1672994 Avatar answered Nov 15 '22 08:11

user1672994