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?

+4
source share
1 answer

In addition to Jon Skeet's comment, you want to add that you can 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 use it ObjectCreationHandling.Reusewith an array, it will not reuse it, but will replace it anyway (well, in any case, it will not be able to reuse it).

Since you wrote that you were expecting a new collection during deserialization, this might help you.

+3
source

Source: https://habr.com/ru/post/1657289/


All Articles