Simple Object Comparer that generates a Diff between objects and is able to Patch one object to transforms into the other.
ObjectDiffPatch uses Newtonsoft.Json internally to create a JObject that we use to run a simple and reliable deep/recursive object comparison.
- Deep/recursive comparison
- Reliable
- Diff
- Patch
You can install using NuGet, see SimpleHelpers.ObjectDiffPatch at NuGet.org
PM> Install-Package SimpleHelpers.ObjectDiffPatchThe nuget package contains C# source code.
The source code will be installed in your project with the following file system structure:
|-- <project root>
|-- SimpleHelpers
|-- ObjectDiffPatch.cs
If you prefer, you can also download the source code: ObjectDiffPatch.cs
Tested with versions 6 and later.
Compares two objects and generates the differences between them returning an object listing all changes.
Detected changes are expressed as two Newtonsoft.Json.Linq.JObject, old and new values.
var diff = ObjectDiffPatch.GenerateDiff (originalObj, updatedObj);
// original properties values
Console.WriteLine (diff.OldValues.ToString());
// updated properties values
Console.WriteLine (diff.NewValues.ToString());Creates an object snapshots as a Newtonsoft.Json.Linq.JObject.
var snapshot = ObjectDiffPatch.Snapshot (obj);
// do something....
do_something (obj);
// log changes
var diff = ObjectDiffPatch.GenerateDiff (snapshot, obj);
if (!diff.AreEqual)
{
Console.WriteLine (diff.NewValues.ToString());
}Modifies an object according to a diff.
var diff = ObjectDiffPatch.GenerateDiff (originalObj, updatedObj);
// recreate originalObj from updatedObj
var patched = ObjectDiffPatch.PatchObject (updatedObj, diff.OldValues);Gets or sets the default newtonsoft json serializer settings.
// enable circular reference handling
ObjectDiffPatch.DefaultSerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;The default serializer settings are exposed in ObjectDiffPatch.DefaultSerializerSettings.
You can change the default settings to enable circular references.
The resulting json will have additional fields $id/$ref to mark the object references.
For more details of the inner workings see http://www.newtonsoft.com/json/help/html/PreserveReferencesHandlingObject.htm
// enable circular reference handling
ObjectDiffPatch.DefaultSerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;