一尘不染

Json.Net PopulateObject追加列表而不是设置值

json

我正在使用Json.Net for .Net 4.5,并且在以下对象上使用填充对象时,它会使用json的内容而不是设置其值来增加List的值。

Json.Net

JsonConvert.PopulateObject(string, object)

class MySettingSubClass
{
    public List<string> MyStringList1 = new List<string>(){"one", "two", "three"}
}

class MySetting
{
    public string MyString = "MyString";
    public int MyInt = 5;
    public MySettingSubClass MyClassObject = new MySettingSubClass();
    public List<string> MyStringList2 = new List<string>{"one", "two", "three"};
}

当它们最初加载时,一切都正确,但是从JSON重新加载两个MyStringLists都是重复的 "one", "two", "three", "one", "two", "three"


阅读 666

收藏
2020-07-27

共1个答案

一尘不染

您应该告诉Json.Net替换数组,如下所示:

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


JsonConvert.PopulateObject(jasonString, myObject, serializerSettings)
2020-07-27