Home > Net >  Why does deserialization append to an initialized `List<T>` instead of overwriting it?
Why does deserialization append to an initialized `List<T>` instead of overwriting it?

Time:01-09

I have a configuration-related data model which is required to have default values for all properties to ensure proper execution of consuming operations. Take for example this very simple model:

public class Sample {
    public List<int> Integers { get; set; }
    public Sample() =>
        Integers = new List<int> { 1 };
}

This model is expected to contain at least one value so we specify a default processing value based on predefined requirements. However, the value doesn't have to be 1 specifically and if a client specifies a different value or many different values, our process should respect their input. Assume the client specifies the following json configuration to be deserialized into the model:

{
    "integers": [ 2, 3 ]
}

During runtime, we load the configuration directly, but let's use a local string variable for the sake of this question:

using Newtonsoft.Json
...
string configuration = "{ \"integers\": [ 2, 3 ] }";
var sample = JsonConvert.DeserializeObject<Sample>(configuration);
Console.WriteLine(string.Join(",", sample.Integers));

The above code snippet should produce an output of:

1,2,3

As you can see in my screenshot below, that is the case: Screenshot showing the previous code snippets along with an overlay of a console window displaying the aforementioned output.

However, my question is why... Why does the deserialization process append to the collection instead of overwriting it?

CodePudding user response:

You can point how to deserialize the json

var serializerSettings = new JsonSerializerSettings {
ObjectCreationHandling = ObjectCreationHandling.Replace};

var sample = JsonConvert.DeserializeObject<Sample>(configuration,serializerSettings);

Console.WriteLine(string.Join(",", sample.Integers)); // [2,3]

by default it is auto, and if there is something it tries to add.

  • Related