What’s the best way to compare two JSON strings in Java? I want to be able to print out only the difference in key/values pairs.
I’m using gson library to convert it to a map and do assert but it displays both JSONs:
Type type = new TypeToken<Map<String, String>>() {}.getType();
Gson gson = new Gson();
Map<String, String> mapExpected = gson.fromJson(expectedJson, type);
Map<String, String> mapResponse = gson.fromJson(jsonResponse, type);
Assert.assertEquals(mapExpected, mapResponse);
Is there a better way to do this?
It is tricky, but it can be done.
I would implement a Pair class that holds both String (key and value), with its corresponding equals() and hashcode();
Then put all elements from Map A as Pair in a Set (
setA) and all elements from Map B in another Set (setB)Then calculate
In
resultthere are only the elements that do not match. If all elements match (both original maps are equal) thenresultis empty.