Json.net deserializing list gives duplicate items

I'm pretty sure that this post is not relevant anymore, but for future reference, here a working solution. Just need to specify that ObjectCreationHandling is set to Replace, i.e. Always create new objects and not to Auto (which is the default) i.e. Reuse existing objects, create new objects when needed.

var data = new SomeData(); 
var json = JsonConvert.SerializeObject(data);
Console.WriteLine("First : {0}", json);
var data2 = JsonConvert.DeserializeObject<SomeData>(json, new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace });
var json2 = JsonConvert.SerializeObject(data2);
Console.WriteLine("Second: {0}", json2);

That is because you are adding items in the constructor. A common approach in deserializers when processing a list is basically:

  • read the list via the getter
    • if the list is null: create a new list and assign via the property setter, if one
  • deserialize each item in turn, and append (Add) to the list

this is because most list members don't have setters, i.e.

public List<Foo> Items {get {...}} // <=== no set

Contrast to arrays, which must have a setter to be useful; hence the approach is usually:

  • deserialize each item in turn, and append (Add) to a temporary list
  • convert the list to an array (ToArray), and assign via the setter

Some serializers give you options to control this behavior (others don't); and some serializers give you the ability to bypass the constructor completely (others don't).

Tags:

C#

Json

Json.Net