Skip to content

feat: JSON diff function with modes #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,51 @@ JsonAddress a = obj.asA(JsonAddress.class); // throws exception, no < 1
```
Both `isA` and `asA` can also be limited to a given set of validation `Rule`
types.


## Comparing JSON values (diff)
When asserting that the JSON returned by a service contains
the expected information a usual challenge is that the
comparison cannot rely on a specifics such as

* the whitespace (formatting)
* the order of properties in objects
* the order of elements in an array that is a "set"
* the presence of additional object properties
* the exact way numbers are formatted

To make such comparisons easy the `diff` method can be used
to find the differences between two `JsonValue` instances.
When computing the difference the comparison can be configured
using the `JsonDiff.Mode`.

```java
JsonValue expected = JsonValue.of( "[1,2,3]" );
JsonValue actual = JsonValue.of( "[1,3,2]" );

JsonDiff diff1 = expected.diff( actual ); // is different
JsonDiff diff2 = expected.diff( actual, JsonDiff.Mode.LENIENT); // same
```

To adjust individual properties of `JsonObject` subtypes the `default`
methods of its properties can be annotated with `@AnyOrder` and
`@AnyAdditional` to opt into a lenient handling.

```java
interface MyObject extends JsonObject {

@JsonDiff.AnyOrder
default JsonArray tags() {
return getArray( "tags" );
}
}
```
The used `Mode` is now overridden for the annotated property:
```java
MyObject expected = JsonValue.of( """
{"tags": ["hello", "intro"]}""" ).as( MyObject.clas );
MyObject actual = JsonValue.of( """
{"tags": ["intro", "hello"]}""" ).as( MyObject.clas );

JsonDiff diff1 = expected.diff( actual ); // same
```
Loading