本文介紹了Json.Net PopulateObject 追加列表而不是設置值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我在 .Net 4.5 中使用 Json.Net,當在以下對象上使用填充對象時,它會使用 json 的內容來增加 List 的值,而不是設置它的值.
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 都是重復的 one"、two"、three"、one"、two"、three"
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)
這篇關于Json.Net PopulateObject 追加列表而不是設置值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!