I have a program where I compare two response bodies, but I do not know what the bodies look like so instead of de-serializing them into Java objects I keep them as JsonNode objects. Suppose I have the following two JsonNode objects:
{
"name": "Bob",
"Age": 30,
"id": 1,
"status" : {
"active": "true",
"address": "123 Main St"
}
}
and
{
"name": "Bob",
"Age": 30,
"status" : {
"active": "true"
}
}
The second JsonNode object is missing the id
and status.address
fields. However, for the fields that exist for both JsonNode objects they are equal. When comparing them I want to ignore comparing missing fields, and just compare on the fields that exist in both JsonNode objects. Again, I cannot de-serialize them into objects and compare that way via Jackson annotations. So my constraints are:
- I do not know how the response bodies will look at runtime, but all the fields of the first JsonNode will appear in the second JsonNode, but the second JsonNode may have fields that dont exist in the first JsonNode.
- Compare the fields that appear in both JsonNode objects
Is there any way to achieve this with Jackson, and if so could someone point to the documentation for it? I would assume I would have to write my own comparator, but any existing literature on this would be helpful.
2
Answers
You need to write custom comparison. One option is to use
JsonNode.equals(Comparator, JsonNode)
with custom comparator. But since you don’t care about ordering it may be better to go just for equality check. The example below uses recursion to check nodes depth-first. Depending on the actual use case you may need to switch to a breadth-first algorithm.Note that the example does not take into consideration possibility of comparing two arrays.
You may try library Josson & Jossons to compare the two JSON datasets by operator:
Subtract right from left
<-<
orSubtract left from right
>->
It handles array comparison as well.
https://github.com/octomix/josson
Output