weichch / system-text-json-jsondiffpatch

High-performance, low-allocating JSON object diff and patch extension for System.Text.Json. Support generating patch document in RFC 6902 JSON Patch format.
MIT License
102 stars 13 forks source link

Add semantic comparisons to DeepEquals extension #5

Closed weichch closed 2 years ago

weichch commented 2 years ago

DeepEquals method currently only implements syntactic equality that compares the raw text of two JsonNode if both backed by JsonElement.

For example, the below test will fail:

var array1 = JsonNode.Parse("[ 1 ]");
var array2 = JsonNode.Parse("[ 1.0 ]");

Assert.True(array1.DeepEquals(array2));

but, can pass for

var array1 = JsonNode.Parse("[         1           ]");
var array2 = JsonNode.Parse("[1]");

Assert.True(array1.DeepEquals(array2));

This is not the case for only one JsonNode backed by JsonElement as the method is already trying to deserialize the JSON representation into .NET types and do semantic comparison.

The following test can pass:

var array1 = new JsonArray(JsonValue.Create(1m));
var array2 = JsonNode.Parse("[1.0]");

Assert.True(array1.DeepEquals(array2));

There should be option/argument to allow using syntactic and semantic IEqualityComparer<JsonElement> implementations when calling the method.

Also see some discussions here.

This may also block adding JsonDocument support.

weichch commented 2 years ago

There is also unnecessary allocation incurred by boxing/unboxing in current comparer, might need to look for a fix. So bumping up version number to 1.1.0.

var value = JsonValue.Create(1);
value.TryGetValue<object>(out var obj) // unnecessary boxing