1

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 ?

BitQuestions
  • 651
  • 7
  • 14
  • 2
    It's a old similar question. Maybe a more recent solution exists? But wait, it can help :https://stackoverflow.com/questions/20270266/json-net-populateobject-appending-list-rather-than-setting-value – vernou Aug 04 '21 at 09:18

1 Answers1

0

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

Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17