1

I have a json file like this:

{
   "foo": "bar",
   "1": 0,
   "array": [
      "foo",
      "bar"
   ]
}

and I can access "foo" and "1" like this:

using Newtonsoft.Json

JObject o = JObject.Parse(json)
Console.WriteLine((string)o["foo"]) // prints "bar"
Console.WriteLine((int)o["1"]) // prints 0

But how can I access the array? I need a string array string[].

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Neins
  • 121
  • 5
  • 4
    what is stopping you from checking what `o["array"]` returns? (i mean instance of what class) then prolly you can check docs how to iterate such object – Selvin May 25 '22 at 07:39

3 Answers3

4
JArray jsonArray = (JArray)o["array"];
string[] stringArray = jsonArray.ToObject<string[]>();
  • The indexer operator of JObject returns a JToken which needs to be converted to JArray
  • You can call the ToObject on it where you can specify the return type as string array

UPDATE #1

Well, you don't need to explicitly cast JToken to JArray, since the ToObject is defined on the JToken. So the following code would be enough:

var stringArray = o["array"].ToObject<string[]>();
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
1

You can get a string array from the JArray by using:

o["array"].Select(x => x.Value<string>()).ToArray()
Markus
  • 20,838
  • 4
  • 31
  • 55
  • 2
    Or something like `((JArray)o["Array"]).ToObject()`. And for your code, I don't think you need the `Children` part, as the JToken already has an IEnumerable interface. – JHBonarius May 25 '22 at 07:51
  • @JHBonarius thanks for the hint, I've removed the `Children` part. – Markus May 25 '22 at 08:16
0

You can gain access to the array (an instance of JArray) by using:

JArray arr = (JArray)o["array"];

To iterate over it's elements, you can use the array's Children method.

Complete code example:

using System;
using Newtonsoft.Json.Linq;

namespace ConsoleAppCS
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonStr = "{ \"foo\": \"bar\", \"1\": 0, \"array\": [ \"foo\", \"bar\" ] }";

            JObject o = JObject.Parse(jsonStr);
            Console.WriteLine((string)o["foo"]); // prints "bar"
            Console.WriteLine((int)o["1"]);      // prints 0
            JArray arr = (JArray)o["array"];
            foreach (var elem in arr.Children())
            {
                Console.WriteLine((string)elem);    // print the array element
            }
        }
    }
}

Output:

bar
0
foo
bar
wohlstad
  • 12,661
  • 10
  • 26
  • 39