我正在寻找一个JSON解析库,支持比较忽略子顺序的两个JSON对象,特别是用于从web服务返回的单元测试JSON。
有任何主要的JSON库支持这一点吗?org。Json库只是做一个引用比较。
我正在寻找一个JSON解析库,支持比较忽略子顺序的两个JSON对象,特别是用于从web服务返回的单元测试JSON。
有任何主要的JSON库支持这一点吗?org。Json库只是做一个引用比较。
当前回答
试试天空尖叫者的圣像。
它的非严格模式有两个主要优点,使其不那么脆弱:
对象的可扩展性(例如,期望值为{id:1},仍然会通过:{id:1,moredata:'x'}。) 宽松的数组排序(例如[‘狗’,‘猫’]= =[“猫”,“狗”])
在严格模式下,它更像json-lib的test类。
测试是这样的:
@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()调用中的参数是expectedJSONString, actualDataString和isStrict。
结果消息非常清晰,这在比较非常大的JSON对象时非常重要。
其他回答
这可能会帮助那些使用Spring Framework的人。你可以重用内部使用的在ResultActions上做断言(用于控制器测试):
进口:org.springframework.test.util.JsonExpectationsHelper
你可以编写带有详细输出的测试:
java.lang.AssertionError: someObject.someArray[1].someInternalObject2.value
Expected: 456
got: 4567
测试代码:
@Test
void test() throws Exception {
final String json1 =
"{" +
" 'someObject': {" +
" 'someArray': [" +
" {" +
" 'someInternalObject': {" +
" 'value': '123'" +
" }" +
" }," +
" {" +
" 'someInternalObject2': {" +
" 'value': '456'" +
" }" +
" }" +
" ]" +
" }" +
"}";
final String json2 =
"{" +
" 'someObject': {" +
" 'someArray': [" +
" {" +
" 'someInternalObject': {" +
" 'value': '123'" +
" }" +
" }," +
" {" +
" 'someInternalObject2': {" +
" 'value': '4567'" +
" }" +
" }" +
" ]" +
" }" +
"}";
new JsonExpectationsHelper().assertJsonEqual(json1, json2, true);
}
org。我已经推出了自己的解决方案,一个与JSONObject实例进行比较的方法。我在那个项目中没有使用复杂的JSON对象,所以我不知道这是否适用于所有场景。此外,鉴于我在单元测试中使用了这个功能,我没有在优化方面投入精力。下面就是:
public static boolean jsonObjsAreEqual (JSONObject js1, JSONObject js2) throws JSONException {
if (js1 == null || js2 == null) {
return (js1 == js2);
}
List<String> l1 = Arrays.asList(JSONObject.getNames(js1));
Collections.sort(l1);
List<String> l2 = Arrays.asList(JSONObject.getNames(js2));
Collections.sort(l2);
if (!l1.equals(l2)) {
return false;
}
for (String key : l1) {
Object val1 = js1.get(key);
Object val2 = js2.get(key);
if (val1 instanceof JSONObject) {
if (!(val2 instanceof JSONObject)) {
return false;
}
if (!jsonObjsAreEqual((JSONObject)val1, (JSONObject)val2)) {
return false;
}
}
if (val1 == null) {
if (val2 != null) {
return false;
}
} else if (!val1.equals(val2)) {
return false;
}
}
return true;
}
其他方法似乎都不太合适,所以我写下了这个:
private boolean jsonEquals(JsonNode actualJson, JsonNode expectJson) {
if(actualJson.getNodeType() != expectJson.getNodeType()) return false;
switch(expectJson.getNodeType()) {
case NUMBER:
return actualJson.asDouble() == expectJson.asDouble();
case STRING:
case BOOLEAN:
return actualJson.asText().equals(expectJson.asText());
case OBJECT:
if(actualJson.size() != expectJson.size()) return false;
Iterator<String> fieldIterator = actualJson.fieldNames();
while(fieldIterator.hasNext()) {
String fieldName = fieldIterator.next();
if(!jsonEquals(actualJson.get(fieldName), expectJson.get(fieldName))) {
return false;
}
}
break;
case ARRAY:
if(actualJson.size() != expectJson.size()) return false;
List<JsonNode> remaining = new ArrayList<>();
expectJson.forEach(remaining::add);
// O(N^2)
for(int i=0; i < actualJson.size(); ++i) {
boolean oneEquals = false;
for(int j=0; j < remaining.size(); ++j) {
if(jsonEquals(actualJson.get(i), remaining.get(j))) {
oneEquals = true;
remaining.remove(j);
break;
}
}
if(!oneEquals) return false;
}
break;
default:
throw new IllegalStateException();
}
return true;
}
要比较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
ModelAssert - https://github.com/webcompere/model-assert可以做到这一点。默认情况下,它更喜欢JSON是有序的,但它可以使用对象键和数组元素的宽松顺序:
assertJson(json1)
.where().keysInAnyOrder().arrayInAnyOrder()
.isEqualTo(json2);
这个断言是AssertJ风格的——即使用流畅的DSL。ModelAssert还可以用于使用相同的DSL构建Hamcrest或Mockito匹配器。
Json可以是字符串、文件、Jackson JsonNode,甚至是自发转换为Json进行比较的POJO。
还支持yml。