Repeated serialization and deserialization creates duplicate items

后端 未结 2 1831
心在旅途
心在旅途 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:06

    Best way would be to configure JSON.Net to replace the default values by

    JsonSerializerSettings   jsSettings =  new JsonSerializerSettings
    {
      ObjectCreationHandling = ObjectCreationHandling.Replace,
    };
    
    JsonConvert.DeserializeObject<Army>(jsonString, jsSettings);
    
    0 讨论(0)
  • 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<Database>(www.text, settings);
    
    0 讨论(0)
提交回复
热议问题