首页 > 解决方案 > How to avoid JsonConvert.PopulateObject enqueue on lists

问题描述

I have this silly class:

public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public List<int> NumbersList { get; set; }
}

And I have this two jsons (the second one coming out from a conditional serialization trough ShouldSerialize)

var json1 = "{\"Name\":\"Joe\",\"Surname\":\"Satriani\",\"Age\":40,\"NumbersList\":[10,20,30]}";
var json2= "{\"Name\":\"Mike\",\"NumbersList\":[40,50,60]}";

Also, I have a silly class to display the results:

private void showResult(object theClass)
{
var result = JsonConvert.SerializeObject(theClass);
Debug.WriteLine("result: " + result);
}

Now, I create a class with the first json:

var myPerson = JsonConvert.DeserializeObject<Person>(json1);

And everything is fine: the class gets all the values it should:

showResult(myPerson);
result: {"Name":"Joe","Surname":"Satriani","Age":40,"NumbersList":[10,20,30]}

Now, I want to apply the second json to the already existing class instance:

JsonConvert.PopulateObject(json2, myPerson);

But... this is what I get:

showResult(myPerson);   
result: {"Name":"Mike","Surname":"Satriani","Age":40,"NumbersList":[10,20,30,40,50,60]}

So, as far as I understand, the PopulateObject correctly rewrites, as expected, the standard field properties (because I don't get "JoeMike" as Name, I get only "Mike" and this if fine), however, it appends list/indexed ones, because I don't obtain "40,50,60" but "10,20,30,40,50,60"...

So, my question is: is there a way to avoid PopulateObject to deliberately append List/Index/Enumerable objects ?

标签: c#json.net

解决方案


In the JsonSerializerSettings class, set the ObjectCreationHandling value to ObjectCreationHandling.Replace. With this setting, the information is no longer appended but copied.

JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
{
   ObjectCreationHandling = ObjectCreationHandling.Replace
};
JsonConvert.PopulateObject(json2, myPerson, jsonSerializerSettings);

ObjectCreationHandling setting


推荐阅读