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[]
.
JArray jsonArray = (JArray)o["array"];
string[] stringArray = jsonArray.ToObject<string[]>();
JObject
returns a JToken
which needs to be converted to JArray
ToObject
on it where you can specify the return type as string arrayUPDATE #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[]>();