Repeated serialization and deserialization creates duplicate items

后端 未结 2 1833
心在旅途
心在旅途 2020-11-30 10:58

Hi everyone i have a problem with my json serealization. I\'m using the Json.NET package under Unity: I\'m searching to make a Database, editable on my application and store

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 11:14

    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(www.text, settings);
    

提交回复
热议问题