public classJsonUtil {public static booleancompareJsonText(String str1, String str2) {returncompareJsonNode(JsonUtil.readTree(str1), JsonUtil.readTree(str2));
}public static booleancompareJsonNode(JsonNode node1, JsonNode node2) {if(node1.isObject()) {if(!node2.isObject()) return false;if(!compareFieldNames(node1.fieldNames(), node2.fieldNames()))return false;
Iterator> fields1 =node2.fields();
Map fields2 =getFields(node1);boolean flag = true;while(fields1.hasNext()){
Entry field1 =fields1.next();
JsonNode field2=fields2.get(field1.getKey());if(!compareJsonNode(field1.getValue(), field2))
flag= false;
}returnflag;
}else if(node1.isArray()) {if(!node2.isArray()) return false;returncompareArrayNode(node1, node2);
}else{returnnode1.toString().equals(node2.toString());
}
}public static booleancompareArrayNode(JsonNode node1, JsonNode node2){
Iterator it1 =node1.elements();while(it1.hasNext()){boolean flag = false;
JsonNode node=it1.next();
Iterator it2 =node2.elements();while(it2.hasNext()){if(compareJsonNode(node, it2.next())){
flag= true;break;
}
}if(!flag)return false;
}return true;
}public static boolean compareFieldNames(Iterator it1, Iteratorit2) {
List nameList1 = new ArrayList();
List nameList2 = new ArrayList();while(it1.hasNext()){
nameList1.add(it1.next());
}while(it2.hasNext()){
nameList2.add(it2.next());
}return nameList1.containsAll(nameList2) &&nameList2.containsAll(nameList1);
}public static MapgetFields(JsonNode node) {
Iterator> fields =node.fields();
Map fieldMap = new HashMap();while(fields.hasNext()){
Entry field =fields.next();
fieldMap.put(field.getKey(), field.getValue());
}returnfieldMap;
}
}