我使用JSONAssert库来比较两个JSON数组。
要比较的数组如下所示:
实际
{"components": [
{
"createdAt": "2022-03-03T10:22:01.959148348Z",
"createdBy": "abc",
"category": "category-1",
"uuid": "469ba1b0-5975-49a0-8fa9-4f3ae5436c68"
},
{
"createdAt": "2022-03-03T10:22:01.959152770Z",
"createdBy": "def",
"category": "category-2",
"uuid": "494e0510-c322-4a45-a103-227b5a3a0adc"
}]
}期望的
{"components": [
{
"createdAt": "2022-03-02T06:58:18.532605787Z",
"createdBy": "def",
"category": "category-2",
"uuid": "78846bb4-5721-447b-ba8b-7fe91bc125a5"
},
{
"createdAt": "2022-03-02T06:58:18.532613344Z",
"createdBy": "abc",
"category": "category-1",
"uuid": "dfe61f6b-addf-442a-8f7c-6e3f249cb4be"
}]
}这是密码。
ObjectMapper objectMapper = new ObjectMapper();
try {
JSONObject actual = new JSONObject(objectMapper.writeValueAsString(actualEntity.getObj())); // actualEntity and expectedEntity are deserialized with Jackson
JSONObject expected = new JSONObject(objectMapper.writeValueAsString(expectedEntity.getObj()));
ArrayValueMatcher<Object> arrValMatch = new ArrayValueMatcher<>(new CustomComparator(
JSONCompareMode.LENIENT,
new Customization("components[*].createdAt", (o1, o2) -> true),
new Customization("components[*].uuid", (o1, o2) -> true)));
Customization arrayValueMatchCustomization = new Customization("components", arrValMatch);
CustomComparator customArrayValueComparator = new CustomComparator(
JSONCompareMode.LENIENT,
arrayValueMatchCustomization);
JSONAssert.assertEquals(expected.toString(), actual.toString(), customArrayValueComparator);
} catch (JsonProcessingException | JSONException e) {
Assert.fail("Something went wrong while parsing JSON: " + e.getMessage());
}以下是错误:
java.lang.AssertionError: components[0].category
Expected: category-2
got: category-1
; components[0].createdBy
Expected: def
got: abc
; components[1].category
Expected: category-1
got: category-2
; components[1].createdBy
Expected: abc
got: def我不明白为什么在这里比较失败,而实际上它应该通过LENIENT比较模式。
发布于 2022-03-07 02:08:51
因为我没有找到OP中提到的问题的解决方案,所以我最终使用了另一个库,称为json-单元-断言j。
我的代码工作,现在看起来是这样的。
import net.javacrumbs.jsonunit.core.Option;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
String actualComponents = objectMapper.writeValueAsString(actualEntity.getComponents());
String expectedComponents = objectMapper.writeValueAsString(expectedEntity.getComponents());
assertThatJson(actualComponents)
.when(Option.IGNORING_ARRAY_ORDER)
.whenIgnoringPaths("[*].createdAt", "[*].uuid")
.isArray()
.isEqualTo(expectedComponents);PS:我没有把这个标记为一个被接受的答案,因为它并没有真正回答OP中的问题。
https://stackoverflow.com/questions/71335815
复制相似问题