Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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"};
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
243 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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


JsonConvert.PopulateObject(jasonString, myObject, serializerSettings)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...