【问题标题】:Compare JSON ignore ID value?比较 JSON 忽略 ID 值?
【发布时间】:2018-06-05 09:44:12
【问题描述】:

我正在使用 JSON Unit 来比较两个 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"
}
]
}

【问题讨论】:

  • 确保您使用的是最新版本的 JsonUnit 依赖项并查看此 post
  • 哪个帖子?我使用的是 1.29.1 版
  • 点击我超链接的帖子。
  • 我已经尝试过这里的解决方案.. 仍然选择那些不同的 id。

标签: java json compare assert


【解决方案1】:

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

JsonAssert.setOptions(IGNORING_VALUES);

【讨论】:

    【解决方案2】:

    使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-29
      • 2018-07-05
      • 1970-01-01
      • 2013-10-03
      • 2014-02-13
      • 2014-05-14
      • 2023-03-07
      • 2016-11-01
      相关资源
      最近更新 更多