Search code examples
c#arraysjsonjson.net

JSON Array Iteration 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?
}

Solution

  • 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