我想比较 Java 8 中的两个 JSON 字符串是否相等,但忽略特定的已知节点,这些节点包含预期不同的值并且是可以容忍的差异,例如时间戳。目前使用来自 org.SkyScreamer 的 JSONAssert v1.5.0,我能够“忽略”其中一些节点,但不能“忽略”数组中的节点。
我想要扩展我当前的 JSONComparator 以包含一个自定义,它的第一个“路径”参数具有一个数组地址。
JSONComparator customisedJobComparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,
new Customization("id", (o1, o2) -> true),
new Customization("appointmentBookedDate.$date", (o1, o2) -> true),
...
new Customization("someArray[n].timestamp", (o1, o2) -> true) //<--- this is wrong, what is the correct way for this path address?
);
下面的代码是我试图证明解决方案的尝试;除了 anArray[].id 值之外,预期/实际 JSON 字符串都是相同的。我希望此测试通过,但失败并出现错误:java.lang.AssertionError: anArray[0] 找不到元素 {"id":"valueA"} 的匹配项
@Test
public void compareJsonStrIgnoringDiffInArray() {
String errorMsg = "";
String expectedJsonStr = "{\"anArray\": [{\"id\": \"valueA\"}, {\"colour\": \"Blue\"}]}";
String actualJsonStr = "{\"anArray\": [{\"id\": \"valueB\"}, {\"colour\": \"Blue\"}]}";
//Create custom comparator which compares two json strings but ignores reporting any differences for anArray[n].id values
//as they are a tolerated difference
Customization customization = new Customization("anArray[n].id", (o1, o2) -> true);
JSONComparator customisedComparator = new CustomComparator(JSONCompareMode.NON_EXTENSIBLE, customization);
JSONAssert.assertEquals(errorMsg, expectedJsonStr, actualJsonStr, customisedComparator);
}