Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Net PopulateObject Appending list rather than setting value

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"

like image 808
rjinski Avatar asked Nov 28 '13 15:11

rjinski


1 Answers

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

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


JsonConvert.PopulateObject(jasonString, myObject, serializerSettings)
like image 144
Reda Avatar answered Nov 07 '22 22:11

Reda