2

Im using Json.Net to serialize and deserialize objects in my project. I have found something strange, that I dont understand. I have reproduced it in a small sample app that looks like this.

public class ClassA
{
    public ClassA()
    {
        ObjectList = new List<ClassB>
        {
            new ClassB{SomeProperty="Test1"},
            new ClassB{SomeProperty="Test2"}
        };
    }
    public List<ClassB> ObjectList { get; set; }
}

public class ClassB
{
    public string SomeProperty { get; set; }
}

[TestClass]
public class Class1Tests
{
    [TestMethod]
    public void SerializeAndDeSerilize_ShouldOnlyShowTwoItemsInList()
    {
        var classA = new ClassA();

        var raw = JsonConvert.SerializeObject(classA);

        var newClassA = JsonConvert.DeserializeObject<ClassA>(raw);

        Assert.AreEqual(2, newClassA.ObjectList.Count); //This fails because its actually 4 items in the list.
    }
}

I was expecting the deserializer to work like this (on a high level): 1. Create instance of object (calling constructor and this creating a collection with 2 items) 2. Deserialize the collection part of the of the json-object and overwrite the collection property with the deserialized collection.

But instead it appears like its adding the items. Am supposed to do something else in this case? I want to make sure I have two items in my list when I create ClassA. But because of this its adding two items everytime I deserialize.

Edit 1: This is the created Json-string: "{\"ObjectList\":[{\"SomeProperty\":\"Test1\"},{\"SomeProperty\":\"Test2\"}]}"

Erik83
  • 539
  • 3
  • 5
  • 19
  • Create a second constructor with a dummy param and move the initialization to that constructor, the deserializer will call the one without param and the collection will be created by the deserializer instead of adding the data and when you create the class use the constructor with the dummy param. – Gusman Sep 19 '17 at 12:43
  • That was my initial idea for solution. But it seems like a annoying workaround... – Erik83 Sep 19 '17 at 13:04
  • @Erik83 You can fix this problem by changing the `ObjectCreationHandling` setting to `Replace` (instead of `Reuse`). See the linked duplicate question. – Brian Rogers Sep 19 '17 at 15:09

0 Answers0