I have a class with some properties, one of them a list of items. All of them are initialized in the default parameterless constructor of the class. I only want to have to have this constructor that initalizes everything.
This is a case for many of my classes.
public class ExampleClass
{
public ExampleClass()
{
this.ListProperty = new List<int> { 1, 2 };
this.APropertyToBeNull = new TypeA();
this.BPropertyToBeNull = new TypeB();
}
public List<int> ListProperty { get; set; }
public TypeA APropertyToBeNull { get; set; }
public TypeB BPropertyToBeNull { get; set; }
}
I create an instance of this class, I set some of the properties to null and I modify the list property to have 2 items.
var instance = new ExampleClass();
instance.APropertyToBeNull = null;
instance.BPropertyToBeNull = null;
instance.ListProperty = new List<int> { 3 };
var raw = JsonConvert.SerializeObject(instance);
var deserialized = JsonConvert.DeserializeObject<ExampleClass>(raw, settings);
Assert.AreEqual(1, deserialized.ListProperty.Count);
Assert.IsNull(deserialized.APropertyToBeNull);
Assert.IsNull(deserialized.BPropertyToBeNull);
When I deserialize, I don't find a way of getting the item exactly as I serialized it. I got two options:
- If I set the ObjectCreationHandling to Replace, the list deserializes fine, but the null properties are not null anymore. The constructor initialized everything, the deserialization replaced the list completely but it did not set the null properties to null.
- If I set the ObjectCreationHandling to Auto or Reuse, the null properties are deserialized fine as null, but the list has the items that were initialized in the constructor plus the items in the JSON. I only want those in the JSON.
How do I get the exact same item I serialized without removing the initialization of all the properties in the constructor (I still want to have all of them initialized in case a new instance is created).
I have played with all possible settings of the serializer, and I don't find a solution.
As a further constraint, I don't want to add attributes to all of my classes. I have this problem for many of them.