Class JsonDiffGenerator
Default implementation of IJsonDiffGenerator that generates RFC 6902 compliant JSON Patch documents.
public class JsonDiffGenerator : IJsonDiffGenerator
- Inheritance
-
objectJsonDiffGenerator
- Implements
Examples
Basic usage:
using SpecWorks.JsonDiff;
using System.Text.Json.Nodes;
var source = JsonNode.Parse("{\"name\":\"Alice\",\"age\":30}");
var target = JsonNode.Parse("{\"name\":\"Alice\",\"age\":31,\"city\":\"NYC\"}");
var generator = new JsonDiffGenerator();
var patch = generator.CreateDiff(source, target);
// Apply the patch
patch.ApplyTo(source);
// source now equals target
Remarks
This class serves as a facade that hides the internal implementation details. The current version (v1.x) uses an adapter pattern with SystemTextJson.JsonDiffPatch as the underlying implementation.
Future versions (v2.x) will use a native SpecWorks-generated RFC 6902 implementation, but the public API will remain unchanged, ensuring seamless migration for consumers.
This component strictly implements RFC 6902 and does not support other formats such as JSON Merge Patch (RFC 7386) or proprietary diff formats. This constraint ensures interoperability and standards compliance.
Constructors
JsonDiffGenerator()
Initializes a new instance of the JsonDiffGenerator class.
public JsonDiffGenerator()
Methods
CreateDiff(JsonNode, JsonNode)
Creates an RFC 6902 JSON Patch document representing the differences between the source and target JSON documents.
public JsonPatchDocument CreateDiff(JsonNode source, JsonNode target)
Parameters
sourceJsonNodeThe source JSON document to compare from.
targetJsonNodeThe target JSON document to compare to.
Returns
- JsonPatchDocument
A Microsoft.AspNetCore.JsonPatch.JsonPatchDocument containing RFC 6902 operations (add, remove, replace, move, copy, test) that transform the source into the target.
Examples
var source = JsonNode.Parse("{\"name\":\"Alice\",\"age\":30}");
var target = JsonNode.Parse("{\"name\":\"Alice\",\"age\":31,\"city\":\"NYC\"}");
var generator = new JsonDiffGenerator();
var patch = generator.CreateDiff(source, target);
// Result: [
// { "op": "replace", "path": "/age", "value": 31 },
// { "op": "add", "path": "/city", "value": "NYC" }
// ]
Remarks
The returned patch document can be applied to the source document using standard JSON Patch implementations to produce the target document.
RFC 6902 Operations:
- add: Add a value to an object or array
- remove: Remove a value from an object or array
- replace: Replace a value
- move: Move a value from one location to another
- copy: Copy a value from one location to another
- test: Test that a value at path equals specified value
Exceptions
- ArgumentNullException
Thrown when
sourceortargetis null.