栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

比较两个JSON时忽略特定的节点/属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

比较两个JSON时忽略特定的节点/属性

您可以为此使用自定义。例如,如果您需要忽略名为“ timestamp”的顶级属性,请使用:

JSONAssert.assertEquals(expectedResponseBody, responseBody, new CustomComparator(JSONCompareMode.LENIENT,     new Customization("timestamp", (o1, o2) -> true)));

也可以使用路径表达式,例如“
entry.id”。在自定义中,您可以使用任何喜欢的方法比较两个值。上面的示例始终返回true,无论期望值和实际值是多少。如果需要,您可以在那里做更复杂的事情。

完全可以忽略多个属性的值,例如:

@Testpublic void ignoringMultipleAttributesWorks() throws JSonException {    String expected = "{"timestamp":1234567, "a":5, "b":3 }";    String actual = "{"timestamp":987654, "a":1, "b":3 }";    JSONAssert.assertEquals(expected, actual, new CustomComparator(JSONCompareMode.LENIENT,         new Customization("timestamp", (o1, o2) -> true),         new Customization("a", (o1, o2) -> true) ));}

使用自定义项时有一个警告:要以自定义方式比较其值的属性必须存在于实际JSON中。如果即使属性根本不存在,也希望比较成功,则必须重写CustomComparator,例如:

@Testpublic void extendingCustomComparatorToAllowToCompletelyIgnoreCertainAttributes() throws JSonException {    // AttributeIgnoringComparator completely ignores some of the expected attributes    class AttributeIgnoringComparator extends CustomComparator{        private final Set<String> attributesToIgnore;        private AttributeIgnoringComparator(JSonCompareMode mode, Set<String> attributesToIgnore, Customization... customizations) { super(mode, customizations); this.attributesToIgnore = attributesToIgnore;        }        protected void checkJsonObjectKeysExpectedInActual(String prefix, JSonObject expected, JSonObject actual, JSonCompareResult result) throws JSonException { Set<String> expectedKeys = getKeys(expected); expectedKeys.removeAll(attributesToIgnore); for (String key : expectedKeys) {     Object expectedValue = expected.get(key);     if (actual.has(key)) {         Object actualValue = actual.get(key);         comparevalues(qualify(prefix, key), expectedValue, actualValue, result);     } else {         result.missing(prefix, key);     } }        }    }    String expected = "{"timestamp":1234567, "a":5}";    String actual = "{"a":5}";    JSONAssert.assertEquals(expected, actual, new AttributeIgnoringComparator(JSONCompareMode.LENIENT,         new HashSet<>(Arrays.asList("timestamp"))) );}

(使用这种方法,您仍然可以使用“自定义”以所需的方式比较其他属性的值。)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508534.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号