Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two JsonNodes with Jackson?

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);
}
like image 804
John Avatar asked Dec 20 '18 15:12

John


People also ask

How do you compare two JSON responses?

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.

How do I compare two JSON files?

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.

Can we compare two JSON objects?

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.


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

like image 87
user7294900 Avatar answered Sep 27 '22 18:09

user7294900


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;
}
like image 36
Karol Dowbecki Avatar answered Sep 27 '22 17:09

Karol Dowbecki