Json.Net PopulateObject附加列表而不是设置值
我在.Net 4.5上使用Json.Net,当在下面的对象上使用populate对象时,它会使用json的内容递增List,而不是设置其值。
Json.Net
JsonConvert.PopulateObject(string, object)
类
class MySettingSubClass { public List MyStringList1 = new List(){"one", "two", "three"} } class MySetting { public string MyString = "MyString"; public int MyInt = 5; public MySettingSubClass MyClassObject = new MySettingSubClass(); public List MyStringList2 = new List{"one", "two", "three"}; }
当他们最初加载时,一切都是正确的,但是从JSON重新加载MyStringLists都是重复的"one", "two", "three", "one", "two", "three"
您应该告诉Json.Net替换数组,如下所示:
var serializerSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace}; JsonConvert.PopulateObject(jasonString, myObject, serializerSettings)