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\"}]}"