Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET Why does it Add to List instead of Overwriting?

Tags:

json

c#

json.net

public class MyClass {
    public List<int> myList = new List<int> { 1337 };
    public MyClass() {}
}

var myClass = JsonConvert.DeserializeObject<MyClass>("{myList:[1,2,3]}");
Console.WriteLine(string.Join(",", myClass.myList.ToArray())); //1337,1,2,3

Why does it display 1337,1,2,3 instead of 1,2,3? Is there a way/setting to make JSON.NET overwrite List instead of adding elements to it?

I need a solution that doesn't modify the constructor.

like image 618
RainingChain Avatar asked Mar 18 '15 02:03

RainingChain


1 Answers

If you don't want this behavior, you can change it by passing in a JSONSerializerSettings object that specifies you don't want to reuse existing objects in the instance's members:

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

var myInstance = JsonConvert.DeserializeObject<MyClass>("{myList:[1,2,3]}", settings);
like image 198
Asad Saeeduddin Avatar answered Sep 25 '22 19:09

Asad Saeeduddin