I have JSON objects called Info
which have only strings & look like this :
{
"prop1": "value1",
"prop2": "value1",
"timestamp": "2018-02-28T05:30:10.100Z",
"prop4": "value4",
"prop_N": "I have a total of 10 properties."
}
I want to compare them with an expected JSON object.
For this, I convert expected and actual JSON into Java objects/POJO. My expected JSON can have nulls in any of the 4 properties. If any expected JSON fields are null, then I want my code to not compare those fields. If they are not null, then compare them using String.equals()
, with one exception: for the timestamp
which is always UTC, we have to ignore the seconds & milliseconds.
The result of the comparison will be used in a JUnit assert method to check if the actual JSON received matches the expected JSON.
I have already implemented the code as shown below. But, there are two problems:
- It does not tell you which fields did not match (it simply returns true/false)
- It's very ugly because of the multiple if blocks.
Can someone suggest how to fix these problems ?
public boolean matchesInfo(Info givenInfo) throws Exception {
if (this.getProp1() != null) {
boolean prop1Matching = this.getProp1().equals(givenInfo.getProp1());
if (prop1Matching == false){return false;}
}
// More if blocks like this. Very long and ugly.
// For timestamp comparison, call a custom function to strip seconds, milliseconds.
}