Skip to content

Latest commit

 

History

History
142 lines (89 loc) · 3.52 KB

File metadata and controls

142 lines (89 loc) · 3.52 KB

SimpleHelpers.ObjectDiffPatch

NuGet GitHub license

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.

Features

  • Deep/recursive comparison
  • Reliable
  • Diff
  • Patch

Installation

NuGet Package Details

You can install using NuGet, see SimpleHelpers.ObjectDiffPatch at NuGet.org

PM> Install-Package SimpleHelpers.ObjectDiffPatch

The 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

Download

If you prefer, you can also download the source code: ObjectDiffPatch.cs

Dependencies

Tested with versions 6 and later.

API

GenerateDiff

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());

Snapshot

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());
}

PatchObject

Modifies an object according to a diff.

var diff = ObjectDiffPatch.GenerateDiff (originalObj, updatedObj);

// recreate originalObj from updatedObj
var patched = ObjectDiffPatch.PatchObject (updatedObj, diff.OldValues);

DefaultSerializerSettings

Gets or sets the default newtonsoft json serializer settings.

// enable circular reference handling
ObjectDiffPatch.DefaultSerializerSettings.PreserveReferencesHandling =
    Newtonsoft.Json.PreserveReferencesHandling.All;

FAQ

How to enable circular references?

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;

Project Information