tags:

views:

312

answers:

1

I'm using a Json.NET library. What's the most convenient way of serializing/deserializing arrays in JSON via C#? For example, I'm trying to deserialize the following text (reading from file):

{
    "Name": "Christina",
    "Gender": "female",
    "Favorite_numbers": [11, 25 ,23]
}

I'm reading the text above from file to a variable:

JObject o = JObject.Parse(File.ReadAllText("input.txt"))

And then, when I'm trying to extract an array [11, 24, 23] with the

int[] num = (int[]) o["Favorite_numbers"]

I receive an error.

What am I doing wrong? How do I correctly read an array? How do I correctly read a 2-dim arrays of the following kind [[1, 2, 3], [4, 5, 6]]?

+1  A: 

The Favorite_numbers property is going to be of type JArray since there is no way for it to infer what type it should be. The most convenient way of deserializing that object is going to be to define a C# class for it and use the JsonConvert.DeserializeObject<T>(...) method(s) to deserialize the JSON to your defined class.

Michael Morton