Overlay data from JSON string to existing object instance

Solution 1:

After poking around the source code (so much easier than reading the documentation, eh?) JSON.NET does exactly what I want already:

JsonConvert.PopulateObject(string, object)

See Json.NET: Populate an Object

Solution 2:

Realize - JsonConvert.PopulateObject(string,object) will NOT work for collections.

Even with PreserveReferencesHandling = Objects/Arrays/All and an IReferenceResolver. JSON.NET will not update items in collections. Instead, it will duplicate your collection items.

JSON.NET only uses its ("ref") Preserve Reference identifiers to reuse references read within the serialized JSON. JSON.NET will not reuse instances in existing nested object graphs. We attempted by adding an ID property to all our objects, but JSON.NET IReferenceResolver does not provide the facilities to find & match existing references within collections.

Our solution will be to deserialize JSON into a new object instance and map properties across the 2 instances using either Fasterflect or AutoMapper.

Solution 3:

Note that JsonConvert.PopulateObject

JsonConvert.PopulateObject(json, item, new JsonSerializerSettings());

Simply calls jsonSerializer.Populate (see here)

        string json = "{ 'someJson':true }";

        var jsonSerializer = new JsonSerializer();

        jsonSerializer.Populate(new StringReader(json), item);

So if you need to repeatedly convert a thousand objects, you may get better performance this route, so that a new JsonSerializer is not instantiated every time.