JSON.NET Why does it Add to List instead of Overwriting?

别来无恙 提交于 2019-12-04 04:40:06

问题


public class MyClass {
    public List<int> myList = new List<int> { 1337 };
    public MyClass() {}
}

var myClass = JsonConvert.DeserializeObject<MyClass>("{myList:[1,2,3]}");
Console.WriteLine(string.Join(",", myClass.myList.ToArray())); //1337,1,2,3

Why does it display 1337,1,2,3 instead of 1,2,3? Is there a way/setting to make JSON.NET overwrite List instead of adding elements to it?

I need a solution that doesn't modify the constructor.


回答1:


If you don't want this behavior, you can change it by passing in a JSONSerializerSettings object that specifies you don't want to reuse existing objects in the instance's members:

var settings = new JsonSerializerSettings
{
    ObjectCreationHandling = ObjectCreationHandling.Replace
};

var myInstance = JsonConvert.DeserializeObject<MyClass>("{myList:[1,2,3]}", settings);


来源:https://stackoverflow.com/questions/29113063/json-net-why-does-it-add-to-list-instead-of-overwriting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!