我想比较Java 8中的两个JSON字符串是否相等,但是忽略特定的已知节点,这些节点包含的值应该是不同的并且是可以容忍的差异,例如时间戳记。
当前使用的是来自org.SkyScreamer的JSONAssert v1.5.0,我能够“忽略”许多这样的节点,但是不能“忽略”数组中的节点。
我想要的是扩展当前的JSONComparator使其包含一个自定义项,该自定义项的第一个“path”参数具有数组地址。
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);
}
最佳答案
深入研究javadoc for JSONAssert之后,我看到了一个使用对象数组的示例。从该示例中,我能够修改您的测试用例:
@Test
public void compareJsonStrIgnoringDiffInArray() throws JSONException {
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
ArrayValueMatcher<Object> arrValMatch = new ArrayValueMatcher<>(new CustomComparator(
JSONCompareMode.NON_EXTENSIBLE,
new Customization("anArray[*].id", (o1, o2) -> true)));
Customization arrayValueMatchCustomization = new Customization("anArray", arrValMatch);
CustomComparator customArrayValueComparator = new CustomComparator(
JSONCompareMode.NON_EXTENSIBLE,
arrayValueMatchCustomization);
JSONAssert.assertEquals(expectedJsonStr, actualJsonStr, customArrayValueComparator);
}