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);
}
Comparing json is quite simple, we can use '==' operator, Note: '==' and 'is' operator are not same, '==' operator is use to check equality of values , whereas 'is' operator is used to check reference equality, hence one should use '==' operator, 'is' operator will not give expected result.
You can also directly compare two JSON files by specifying their urls in the GET parameters url1 and url2. Then you can visualize the differences between the two JSON documents. It highlights the elements which are different: Different value between the two JSON: highlight in red color.
Similarly, we can also compare two JSON objects that contain a list element. It's important to know that two list elements are only compared as equal if they have the same values in the exact same order.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With