JSON.NET为什么它添加到列表,而不是覆盖? [英] JSON.NET Why does it Add to List instead of Overwriting?
本文介绍了JSON.NET为什么它添加到列表,而不是覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
为什么它显示1337,1,2,3代替1,2,3?有没有一种方法/设置,使JSON.NET覆盖列表,而不是添加元素呢?
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.
推荐答案
如果你不希望这种行为,你可以通过在 JSONSerializerSettings $ C更改$ C>对象,指定你不想重复使用实例的成员现有对象:
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);
这篇关于JSON.NET为什么它添加到列表,而不是覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文