Json.NET: serialization / deserialization of arrays

I am using the Json.NET library. What is the most convenient way to serialize / deserialize arrays in JSON via C #? For example, I am trying to deserialize the following text (reading from a file):

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

I am reading the text above from a file into a variable:

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

And then when I try to extract an array [11, 24, 23] using

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

I get an error message.

What am I doing wrong? How to read an array correctly? How to read 2-dimensional arrays of the following form [[1, 2, 3], [4, 5, 6]] ?

+6
json arrays
source share
2 answers

The Favorite_numbers property will be of type JArray , because there is no way to determine what type it should be. The most convenient way to deserialize this object is to define a C # class for it and use the JsonConvert.DeserializeObject<T>(...) methods to deserialize the JSON into your specific class.

+2
source share

Depending on what you do. In your case, the easiest way would be to create a JsonConverter . So you can do the following:

 public class IntArrayConverter : JsonCreationConverter<int[]> { protected override int[] Create(Type objectType, JArray jArray) { List<int> tags = new List<int>(); foreach (var id in jArray) { tags.Add(id.Value<int>()); } return tags.ToArray(); } } public abstract class JsonCreationConverter<T> : JsonConverter { /// <summary> /// Create an instance of objectType, based properties in the JSON Array /// </summary> /// <param name="objectType">type of object expected</param> /// <param name="jObject">contents of JSON Array that will be deserialized</param> /// <returns></returns> protected abstract T Create(Type objectType, JArray jObject); public override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JArray jArray = JArray.Load(reader); T target = Create(objectType, jArray); return target; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } 

Then define your model with a new attribute:

 public class Person { public string Name { get; set; } public string Gender { get; set; } [JsonConverter(typeof(IntArrayConverter))] public int[] Favorite_numbers { get; set; } } 

And you can use it as usual:

 Person result = JsonConvert.DeserializeObject<Person>(@"{ ""Name"": ""Christina"", ""Gender"": ""female"", ""Favorite_numbers"": [11, 25 ,23] }"); 
+1
source share

All Articles