比较 JSON 忽略 ID 值?

Compare JSON ignore ID value?

我正在使用 JSON 单位来比较两个 json 响应。 然而,UUID 每次都是动态的,因此响应总是不同的,下面的内容不会忽略 "id" 并始终将其标记为不同。

private void assertWithIgnore(String endpoint, String expected, int code) throws IOException {
    try {
        response.then()
                .statusCode(code)
                .contentType(ContentType.JSON);
        if (compare) {
            assertJsonEquals(response.asString(),
                    resource("expected/" + expected),
                    JsonAssert.whenIgnoringPaths("item[*].id"));
        } else {
            Assert.fail("Not comparing response, write direct to file!");
        }
    } catch (AssertionError error) {
        FileUtils.writeStringToFile(getResultFile(expected), response.prettyPrint());
        failures.put(baseURL + basePath + endpoint, response);
        throw error;
    }
}

下面是 JSON 的一个小例子:

{
"item": [
{
"id": "1",
"title": "Hello"
}
]
}

通过以下方法解决了上述问题:

JsonAssert.setOptions(IGNORING_VALUES);

使用 JsonAssert,这应该也可以工作...准备好了吗?

ArrayValueMatcher<Object> arrayValueMatcher = new ArrayValueMatcher<>(new CustomComparator(JSONCompareMode.LENIENT, new Customization("item[*].id", new ValueMatcher<Object>() {
                    @Override
                    public boolean equal(Object o1, Object o2) {
                        return true;
                    }
                })));

Customization arrayValueMatcherCustomization = new Customization("item", arrayValueMatcher);


CustomComparator customArrayValueComparator = new CustomComparator(JSONCompareMode.LENIENT, arrayValueMatcherCustomization);


JSONAssert.assertEquals(expect, actual, customArrayValueComparator);

我使用的是 1.5.0 版库