测试两个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屋!