Alexander Alexander - 2 months ago 14
C# Question

Newtonsoft.JSON: JSON List and Array are handled differently

Given the following code:

public class ColorList
{
public List<string> Colors = new List<string>(new string[1] { "#eeeeee"});
}
public class ColorArray
{
public string[] Colors = new string[1] { "#eeeeee"};
}

public class Program
{
public static void Main()
{
string json = "{Colors:['#abc','#123']}";

// Deserialize Colors into List:
Console.WriteLine(JsonConvert.DeserializeObject<ColorList>(json).Colors.Count);
// returns 3
// Deserialize Colors into Array:
Console.WriteLine(JsonConvert.DeserializeObject<ColorArray>(json).Colors.Length);
// returns 2
}
}


Why is there a difference between the two deserializations?

Evk Evk
Answer

In addition to Jon Skeet comment, want to add that you may partially control this behavior:

var settings = new JsonSerializerSettings() {
     ObjectCreationHandling = ObjectCreationHandling.Replace
};
Console.WriteLine(JsonConvert.DeserializeObject<ColorList>(json, settings).Colors.Count); // returns 2, because list was replaced, not reused

However, even if you will use ObjectCreationHandling.Reuse with array - it will not reuse it, but still will replace (well it cannot really reuse it anyway).

Since you wrote that you would expect new collection when deserialized - that might help you.