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

有任何主要的JSON库支持这一点吗?org。Json库只是做一个引用比较。


当前回答

有任何主要的JSON库支持这一点吗?org。Json库只是做一个引用比较。

但org。Json支持这个!使用similar()代替equals()。

其他回答

查看答案,我尝试了JSONAssert,但失败了。所以我用Jackson和zjsonpatch。我在SO的答案中发布了详细信息。

您可以使用zjsonpatch库,它根据RFC 6902 (JSON Patch)显示差异信息。它很容易使用。请访问其说明页面了解其用法

我正在使用这个,并为我工作良好(org.json.*):

package com.project1.helpers;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class JSONUtils {

    public static boolean areEqual(Object ob1, Object ob2) throws JSONException {
        Object obj1Converted = convertJsonElement(ob1);
        Object obj2Converted = convertJsonElement(ob2);
        return obj1Converted.equals(obj2Converted);
    }

    private static Object convertJsonElement(Object elem) throws JSONException {
        if (elem instanceof JSONObject) {
            JSONObject obj = (JSONObject) elem;
            Iterator<String> keys = obj.keys();
            Map<String, Object> jsonMap = new HashMap<>();
            while (keys.hasNext()) {
                String key = keys.next();
                jsonMap.put(key, convertJsonElement(obj.get(key)));
            }
            return jsonMap;
        } else if (elem instanceof JSONArray) {
            JSONArray arr = (JSONArray) elem;
            Set<Object> jsonSet = new HashSet<>();
            for (int i = 0; i < arr.length(); i++) {
                jsonSet.add(convertJsonElement(arr.get(i)));
            }
            return jsonSet;
        } else {
            return elem;
        }
    }
}

如果您已经在使用JUnit,那么最新版本现在使用Hamcrest。它是一个通用的匹配框架(对单元测试特别有用),可以扩展以构建新的匹配器。

有一个名为hamcrest-json的小型开源库,它具有json感知匹配。它有良好的文档、测试和支持。以下是一些有用的链接:

源代码 主页 主匹配器的Javadocs:

使用JSON库org.json.simple对象的示例代码:

Assert.assertThat(
    jsonObject1.toJSONString(),
    SameJSONAs.sameJSONAs(jsonObject2.toJSONString()));

可选地,您可以(1)允许“任意顺序”数组和(2)忽略额外的字段。

由于Java有多种JSON库(Jackson, GSON, JSON -lib等),hamcrest-json支持JSON文本(如Java .lang. string),以及原生支持来自Douglas Crockford的JSON库org.json的对象是很有用的。

最后,如果不使用JUnit,可以直接使用Hamcrest进行断言。(我在这里写过。)

要比较json,我建议使用我的JSONCompare库: https://github.com/fslev/json-compare

// Compare by regex
String expected = "{\"a\":\".*me.*\"}";
String actual = "{\"a\":\"some text\"}";
JSONCompare.assertEquals(expected, actual);  // True

// Check expected array has no extra elements
String expected = "[1,\"test\",4,\"!.*\"]";
String actual = "[4,1,\"test\"]";
JSONCompare.assertEquals(expected, actual);  // True

// Check expected array has no numbers
String expected = "[\"\\\\\\d+\"]";
String actual = "[\"text\",\"test\"]";
JSONCompare.assertEquals(expected, actual);  // True

// Check expected array has no numbers
String expected = "[\"\\\\\\d+\"]";
String actual = "[2018]";
JSONCompare.assertNotEquals(expected, actual);  // True