Repeated serialization and deserialization creates duplicate items

The reason this is happening is due to the combination of two things:

  1. Your class constructors automatically add default items to their respective lists. Json.Net calls those same constructors to create the object instances during deserialization.
  2. Json.Net’s default behavior is to reuse (i.e. add to) existing lists during deserialization instead of replacing them.

To fix this, you can either change your code such that your constructors do not automatically add default items to your lists, or you can configure Json.Net to replace the lists on deserialization rather than reusing them. The latter by can be done by changing the ObjectCreationHandling setting to Replace as shown below:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ObjectCreationHandling = ObjectCreationHandling.Replace;

var database = JsonConvert.DeserializeObject<Database>(www.text, settings);

Leave a Comment