import java.util.Iterator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonDiff {
// private static StringBuilder sb = new StringBuilder();
@SuppressWarnings("unchecked")
public static void compareJson(JSONObject json1, JSONObject json2,String key) {
Iterator<String> i = json1.keys();
while (i.hasNext()) {
key = i.next();
compareJson(json1.get(key), json2.get(key),key);
}
// return sb.toString();
}
public static void compareJson(Object json1,Object json2,String key) {
if (json1 instanceof JSONObject) {
compareJson((JSONObject)json1,(JSONObject)json2,key);
}else if (json1 instanceof JSONArray) {
compareJson((JSONArray)json1,(JSONArray)json2,key);
}else if(json1 instanceof String){
compareJson((String)json1,(String)json2,key);
}else {
compareJson(json1.toString(),json2.toString(),key);
}
}
public static void compareJson(String str1,String str2,String key) {
if (!str1.equals(str2)) {
// sb.append("key:"+key+ ",json1:"+ str1 +",json2:"+str2);
System.out.println("key:"+key+ ",json1:"+ str1 +",json2:"+str2);
}
}
public static void compareJson(JSONArray json1,JSONArray json2,String key) {
if(json1 != null && json2 != null){
Iterator i1= json1.iterator();
Iterator i2= json2.iterator();
while ( i1.hasNext()) {
compareJson(i1.next(), i2.next(),key);
}
}
}
}
JSON数映射在java中包括JSONObject,JSONArray,String。
比如下面这段json数据:
{
"username":"tom",
"age":18,
"address":[
{"province":"上海市"},
{"city":"上海市"},
{"disrtict":"静安区"}
]
}
整体是一个JSONObject,字段username和age对应的值是String,字段address对应的是一个JSONArray。而JSONArray的内容又是一段又一段的JSONObject。所以整体代码思路先判断类型,直到类型是String时用字符串比较方法。其余的都需进行循环比较直到类型为String。