在比较两个JSON时忽略特定节点/属性 [英] Ignore specific nodes/attributes while comparing two JSONs

查看:505
本文介绍了在比较两个JSON时忽略特定节点/属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两个JSON字符串,它们是一个巨大的层次结构,并想知道它们在值上的不同之处。但是某些值是在运行时生成的并且是动态的。我想从我的比较中忽略那些特定节点。

I want to compare two JSON strings which is a huge hierarchy and want to know where they differ in values. But some values are generated at runtime and are dynamic. I want to ignore those particular nodes from my comparison.

我目前正在使用 org.SkyScreamer 中的JSONAssert进行比较。它给了我很好的控制台输出,但不会忽略任何属性。

I am currently using JSONAssert from org.SkyScreamer to do the comparison. It gives me nice console output but does not ignore any attributes.

ex。

java.lang.AssertionError messageHeader.sentTime
expected:null
got:09082016 18:49:41.123

现在这是动态的,应该被忽略。类似

Now this comes dynamic and should be ignored. Something like

JSONAssert.assertEquals(expectedJSONString, actualJSONString,JSONCompareMode, *list of attributes to be ignored*)

如果有人在JSONAssert中建议解决方案,那将会很棒。但是也欢迎其他方式。

It would be great if someone suggests a solution in JSONAssert. However other ways are also welcome.

推荐答案

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

You can use Customization for this. For example, if you need to ignore a top-level attribute named "timestamp" use:

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

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

It's also possible to use path expressions like "entry.id". In your Customization you can use whatever method you like to compare the two values. The example above always returns true, no matter what the expected value and the actual value are. You could do more complicated stuff there if you need to.

这篇关于在比较两个JSON时忽略特定节点/属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆