這個比較簡單,項目中用到兩個jsonObject進行merge,是以
這次寫了個工具方法,在這記錄一下,以後備用。
兩個jsonObject進行merge,将object2 merge 到 object1,對object1
進行循環,遞歸進行檢查,若是對應值是Jsonobject繼續進行遞歸,直到葉子
到數組或者數值進行替換。
此次merge隻會增加字段不會減,不說廢話,直接上代碼,代碼看起來
邏輯更清楚
:
public static JSONObject mergeJson(Object object1,Object object2){
if (object1 == null &&object2 == null){
return null;
}
try {
if (object1 == null){
return new JSONObject(object2.toString());
}
if (object2 == null){
return new JSONObject(object1.toString());
}
JSONObject jsonObject1 = new JSONObject(object1.toString());
JSONObject jsonObject2= new JSONObject(object2.toString());
Iterator iterator = jsonObject2.keys();
while (iterator.hasNext()){
String key = (String) iterator.next();
Object value2 = jsonObject2.get(key);
if (jsonObject1.has(key)){
Object value1 = jsonObject1.get(key);
if (!(value1 instanceof JSONObject)){
jsonObject1.put(key,value2);
}else {
jsonObject1.put(key,mergeJson(value1,value2));
}
}else {
jsonObject1.put(key,value2);
}
}
return jsonObject1;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}