Search code examples
c#jsonjson.netlinq-to-json

Newtonsoft json access array inside json


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[].


Solution

  • 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[]>();