import com.alibaba.fastjson.JSONArray; //导入方法依赖的package包/类
private static void mergeJSONArray(JSONArray target, JSONArray from, ArrayMergeStrategy strategy){
switch (strategy) {
case REPLACE:
if (target.size() > from.size()) {
for (int i = 0; i < from.size(); i++) {
target.set(i, from.get(i));
}
} else {
target.clear();
target.addAll(from);
}
break;
case APPEND:
target.addAll(from);
break;
case DEEP_MERGE:
// 对位置相同的元素进行合并;
int mergeCount = Math.min(target.size(), from.size());
Object targetFieldValue;
Object fromFieldValue;
for (int i = 0; i < mergeCount; i++) {
targetFieldValue = target.get(i);
fromFieldValue = from.get(i);
if ((targetFieldValue instanceof JSONObject) && (fromFieldValue instanceof JSONObject)) {
// 都是 JSON 对象,进行深度合并;
mergeJSONObject((JSONObject) targetFieldValue, (JSONObject) fromFieldValue, strategy);
} else if ((targetFieldValue instanceof JSONArray) && (fromFieldValue instanceof JSONArray)) {
// 都是 JSON 数组,进行数组合并;
mergeJSONArray((JSONArray) targetFieldValue, (JSONArray) fromFieldValue, strategy);
} else {
// 类型不同,直接替换;
target.set(i, fromFieldValue);
}
}
// 对多出来的元素进行追加;
if (from.size() > target.size()) {
for (int i = target.size(); i < from.size(); i++) {
target.add(from.get(i));
}
}
break;
default:
throw new IllegalStateException("Unsupported strategy[" + strategy + "] for merging json array!");
}
}