比较Java中的两个JSON对象 [英] Compare two JSON objects 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;
}
这篇关于比较Java中的两个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!