Json.Net PopulateObject追加列表,而不是设定值设定值、而不是、列表、Json

2023-09-03 16:23:44 作者:可爱

我使用Json.Net对于.NET 4.5,当使用填充以下对象对象是递增的列表的使用json的内容,而不是设置它的值。

I am using Json.Net for .Net 4.5 and when using populate object on the following object it increments the List's with the content of the json rather than setting its value.

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被复制一,二,三,一,二,三

When they initially load, all is correct, however reloading from JSON both MyStringLists are duplicated "one", "two", "three", "one", "two", "three"

推荐答案

您应该告诉Json.Net更换阵列,像这样的:

You should tell Json.Net to replace the arrays, like this:

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


JsonConvert.PopulateObject(jasonString, myObject, serializerSettings)