5

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?
}
1
  • @SMeaden, OK, OP updated. Commented Apr 27, 2018 at 18:32

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks user1672994, what's the magic behind Console.WriteLine(obj)? I do need that result in string format, not output to console. I tried string js = JsonConvert.SerializeObject(obj); but got the error of "Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'Newtonsoft.Json.Linq.JObject'"
If you need the value as string, then use the method as var str = obj.Value<string>(); You don't need to serialize the JArray again.
I'm trying to write a library that may get array of int or string as input, that's why I'm trying to serialize it instead of using Value<int>() or Value<string>(). Thx.
Since, the library would expect the Type then make the library method as Generic so that caller will pass the appropriate type. And then in Value method you can pass the same T.
k. Thanks a lot!
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.