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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With