问题
I was hoping to use Jackson to find JSON diff but it does not give detailed error messages.
So I tried using JSOnAssert to find the diff between two JSON strings.
JSONAssert.assertEquals(expectedJsonResponse, actualJsonResponse, false);
Sadly, it does not appear to match correctly and give the detailed error messages as in the examples. If you have used it, Can you please clarify?
java.lang.AssertionError: data[0] Could not find match for element {"errors":[{"httpStatus":"BAD_REQUEST","personId":null,"details":"User ID [UNKNOWN]. Invalid ID: NONSENSE"}],"successfulIds":["A0","B1","C3"]}
at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:222)
Actual JSON:
{"_links":{"self":{"href":"https://myserver.com:1000/api/person/upload? myCsvFile={myCsvFile}","templated":true}},"data":[{"successfulIds":["A0","XYZ","C3"],"errors":[{"personId":null,"httpStatus":"BAD_REQUEST","details":"User ID [UNKNOWN]. Invalid ID: NONSENSE"}]}]}
Expected JSON:
{
"_links": {
"self": {
"href": "https://myserver.com:1000/api/person/upload?myCsvFile={myCsvFile}",
"templated": true
}
},
"data": [
{
"successfulIds": [
"A0",
"B1",
"C3"
],
"errors": [
{
"personId": null,
"httpStatus": "BAD_REQUEST",
"details": "User ID [UNKNOWN]. Invalid ID: NONSENSE"
}
]
}
]
}
回答1:
I tried to email the address at http://jsonassert.skyscreamer.org/ but got a
The following message to jsonassert-dev@skyscreamer.org was undeliverable. The reason for the problem: 5.1.0 - Unknown address error 550-"5.1.1 The email account that you tried to reach does not exist
So I tried ZJsonPatch. I like the fact that using Jackson with it, the ordering of the members does not matter. In other words, I first try to check for equality using Jackson. Jackson is ordering independent. Then if it fails, I use ZJsonPatch to tell me what the diff is.
{"op":"replace","path":"/data/0/successfulIds/1","value":"B9"}
which handles nested JSON well.
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(expectedJsonResponse);
JsonNode actual = mapper.readTree(actualJsonResponse);
try {
assertEquals(expected, actual);
} catch (AssertionError ae) {
JsonNode patch = JsonDiff.asJson(actual, expected);
throw new Exception(patch.toString(), ae);
}
来源:https://stackoverflow.com/questions/62048635/finding-json-diff-fails-using-jsonassert