在Java中比较两个JSON时忽略数组中的特定节点

Mar*_*k H 4 java json jsonassert

我想比较Java 8中的两个JSON字符串是否相等,但忽略特定的已知节点,这些节点包含的值应该不同并且可以忍受,例如时间戳。当前使用的是来自org.SkyScreamer的JSONAssert v1.5.0,我能够“忽略”许多这样的节点,但是不能“忽略”数组中的节点。

我想要扩展当前的JSONComparator,使其包含一个Customization,该Customization的第一个“ 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?
            );
Run Code Online (Sandbox Code Playgroud)

下面的代码是我尝试证明解决方案的尝试;除了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);
}
Run Code Online (Sandbox Code Playgroud)

D.B*_*.B. 5

在深入研究JSONAssertjavadoc之后,我看到了一个使用对象数组的示例。从该示例中,我能够修改您的测试用例:

    @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);
    }
Run Code Online (Sandbox Code Playgroud)

  • 在其他地方没有看到这个。很高兴我碰到了这个。谢谢 (2认同)