0

我希望使用 Jackson 来查找 JSON 差异,但它没有给出详细的错误消息。

所以我尝试使用 JSOnAssert 来查找两个 JSON 字符串之间的差异。

JSONAssert.assertEquals(expectedJsonResponse, actualJsonResponse, false);

遗憾的是,它似乎没有正确匹配并给出示例中的详细错误消息。如果你用过,能解释一下吗?

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)

实际 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"}]}]}

预期的 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"
                }
            ]
        }
    ]
}
4

1 回答 1

1

我试图通过电子邮件发送地址http://jsonassert.skyscreamer.org/但得到了一个

以下发给 jsonassert-dev@skyscreamer.org 的消息无法传递。问题原因:5.1.0 - 未知地址错误 550-》5.1.1 您尝试访问的电子邮件帐户不存在

所以我尝试了 ZJsonPatch。我喜欢这样一个事实,即使用杰克逊,成员的顺序无关紧要。换句话说,我首先尝试使用 Jackson 检查是否相等。杰克逊正在独立订购。然后如果失败,我使用 ZJsonPatch 告诉我差异是什么。

{"op":"replace","path":"/data/0/successfulIds/1","value":"B9"}

它可以很好地处理嵌套的 JSON。

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);
}
于 2020-05-29T14:34:11.387 回答