测试两个 JSON 对象的相等性,忽略 Java 中的子顺序 [已关闭]

2022-08-31 05:21:44

我正在寻找一个JSON解析库,它支持比较两个JSON对象忽略子顺序,专门用于从Web服务返回的单元测试JSON。

是否有任何主要的 JSON 库支持此功能?org.json 库只是做一个引用比较。


答案 1

试试Skyscreamer的JSONAssert

的非严格模式有两个主要优点,使其不那么脆弱:

  • 对象可扩展性(例如,对于预期值 {id:1},这仍然会传递:{id:1,moredata:'x'}
  • 松散数组排序(例如 ['dog','cat']==['cat','dog'])

在严格模式下,它的行为更像是json-lib的测试类。

测试如下所示:

@Test
public void testGetFriends() {
    JSONObject data = getRESTData("/friends/367.json");
    String expected = "{friends:[{id:123,name:\"Corby Page\"}"
        + ",{id:456,name:\"Solomon Duskis\"}]}";
    JSONAssert.assertEquals(expected, data, false);
}

JSONAssert.assertEquals() 调用中的参数是 expectedJSONStringactualDataStringisStrict

结果消息非常清晰,这在比较非常大的 JSON 对象时非常重要。


答案 2

作为一般的体系结构点,我通常建议不要让对特定序列化格式的依赖性超出存储/网络层;因此,我首先建议您考虑测试您自己的应用程序对象之间的相等性,而不是它们的 JSON 表现形式。

话虽如此,我目前是Jackson的忠实粉丝,我对他们的ObjectNode.equals()实现的快速阅读表明,你想要的集合成员资格比较:

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;
}