Json.net deserializing list gives duplicate items

前端 未结 4 1260
眼角桃花
眼角桃花 2021-02-18 15:56

I have just started using Newtonsoft.Json (Json.net). In my first simple test, I ran into a problem when deserializing generic lists. In my code sample below I serialize an obje

4条回答
  •  青春惊慌失措
    2021-02-18 16:35

    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(json, new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace });
    var json2 = JsonConvert.SerializeObject(data2);
    Console.WriteLine("Second: {0}", json2);
    

提交回复
热议问题