测试两个 JSON 对象是否相等,忽略 Java 中的子顺序 [英] Testing two JSON objects for equality ignoring child order in Java
问题描述
我正在寻找一个支持比较两个 JSON 对象而忽略子顺序的 JSON 解析库,专门用于单元测试从 Web 服务返回的 JSON.
I'm looking for a JSON parsing library that supports comparing two JSON objects ignoring child order, specifically for unit testing JSON returning from a web service.
是否有任何主要的 JSON 库支持此功能?org.json 库只是做一个引用比较.
Do any of the major JSON libraries support this? The org.json library simply does a reference comparison.
推荐答案
作为一般架构点,我通常建议不要让对特定序列化格式的依赖超出您的存储/网络层;因此,我首先建议您考虑测试自己的应用程序对象之间的相等性,而不是它们的 JSON 表现形式.
As a general architectural point, I usually advise against letting dependencies on a particular serialization format bleed out beyond your storage/networking layer; thus, I'd first recommend that you consider testing equality between your own application objects rather than their JSON manifestations.
话虽如此,我目前是 Jackson 的忠实粉丝,我快速阅读了他们的ObjectNode.equals() 实施建议进行您想要的集合成员资格比较:
Having said that, I'm currently a big fan of Jackson which my quick read of their ObjectNode.equals() implementation suggests does the set membership comparison that you want:
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o.getClass() != getClass()) {
return false;
}
ObjectNode other = (ObjectNode) o;
if (other.size() != size()) {
return false;
}
if (_children != null) {
for (Map.Entry<String, JsonNode> en : _children.entrySet()) {
String key = en.getKey();
JsonNode value = en.getValue();
JsonNode otherValue = other.get(key);
if (otherValue == null || !otherValue.equals(value)) {
return false;
}
}
}
return true;
}
这篇关于测试两个 JSON 对象是否相等,忽略 Java 中的子顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!