How to compare two JsonNodes with Jackson?

Viewed 10621

I have a method which compares two objects, but I don't know how to compare JsonNode by Jackson library.

I want get something like that:

private boolean test(JsonNode source) {
    JsonNode test = compiler.process(file);
    return test.equals(source);
}
2 Answers

That's good enough to use JsonNode.equals:

Equality for node objects is defined as full (deep) value equality. This means that it is possible to compare complete JSON trees for equality by comparing equality of root nodes.

Maybe also add a null check as test != null

You current code looks ok, the JsonNode class provides JsonNode.equals(Object) method for checking:

Equality for node objects is defined as full (deep) value equality.

Since version 2.6 there is also overloaded version which uses a custom comparator:

public boolean equals(Comparator<JsonNode> comparator, JsonNode other){
    return comparator.compare(this, other) == 0;
}
Related