I am trying to compare two JSON structures using Custom comparator of JSONAssert package. For example,
Data1:
{
"name": "John",
"details": {
"age": 30,
"State": {
"City": "Buffalo",
"Country" :[
{
"Classification" : "USA",
"Data" : "sample1"
},
{
"Classification" : "Canada",
"Data" : "sample1"
}
]
}
}
}
I want to ignore the whole array index 0 when the classification has the value "USA" i.e I want to ignore even the data field in the first element of a country when the classification value is "USA".
public void compareJsonStrIgnoringDiffInArray() throws JSONException {
String errorMsg = "";
String expectedJsonStr = "{\"name\":\"John\",\"details\":{\"age\":30,\"State\":{\"City\":\"Buffalo\",\"Country\":[{\"Classification\":\"USA\",\"Data\":\"sample1\"},{\"Classification\":\"Canada\",\"Data\":\"sample1\"}]}}}";
String actualJsonStr = "{\"name\":\"John\",\"details\":{\"age\":30,\"State\":{\"City\":\"Buffalo\",\"Country\":[{\"Classification\":\"USA\",\"Data\":\"sample1\"},{\"Classification\":\"Canada\",\"Data\":\"sample1\"}]}}}";
//Create custom comparator which compares two json strings but ignores reporting any differences for anArray[n].id values
//as they are a tolerated difference
ArrayValueMatcher<Object> arrValMatch = new ArrayValueMatcher<>(new CustomComparator(
JSONCompareMode.NON_EXTENSIBLE,
new Customization("Country[*].classification", (o1, o2) -> true)));
Customization arrayValueMatchCustomization = new Customization("Country", arrValMatch);
CustomComparator customArrayValueComparator = new CustomComparator(
JSONCompareMode.NON_EXTENSIBLE,
arrayValueMatchCustomization);
JSONAssert.assertEquals(expectedJsonStr, actualJsonStr, customArrayValueComparator);
}
I have tried this implementation but it ignores all the classification values in every index. But i only want one index to be ignored including the data element when the classification value is "USA".
Ref: Ignore specific node within array when comparing two JSON in Java