Commit ecc8c0c3 authored by alex yao's avatar alex yao

feat:Json copy工具

parent af7b7c90
......@@ -3,6 +3,7 @@ package cn.com.poc.common.utils;
import cn.com.yict.framemax.core.utils.BeanUtils;
import cn.com.yict.framemax.core.utils.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.apache.log4j.Logger;
......@@ -156,5 +157,60 @@ public final class JsonUtils {
return deSerialize(serialize, type);
}
/**
* 深度合并两个 JSON 对象
*
* @param source 源 JSON (A)
* @param target 目标 JSON (B)
* @return 合并后的 JSONObject
*/
public static JSONObject deepMerge(JSONObject source, JSONObject target) {
for (String key : source.keySet()) {
Object valueA = source.get(key);
Object valueB = target.get(key);
// 情况1:A的值是嵌套对象
if (valueA instanceof JSONObject) {
if (valueB instanceof JSONObject) {
// 递归合并嵌套对象
deepMerge((JSONObject) valueA, (JSONObject) valueB);
} else {
// B中不存在或不是对象,直接覆盖
target.put(key, cloneJson(valueA));
}
}
// 情况2:A的值是数组
else if (valueA instanceof JSONArray) {
target.put(key, cloneJson(valueA)); // 数组直接覆盖
}
// 情况3:A的值是基本类型
else {
if (isNotEmpty(valueA)) {
target.put(key, valueA); // 非空时覆盖
} else if (!target.containsKey(key)) {
target.put(key, valueA); // B中不存在时添加
}
}
}
return target;
}
/**
* 判断值是否非空(扩展空值检测)
*/
private static boolean isNotEmpty(Object value) {
if (value == null) return false;
if (value instanceof String) return !((String) value).isEmpty();
if (value instanceof JSONObject) return !((JSONObject) value).isEmpty();
if (value instanceof JSONArray) return !((JSONArray) value).isEmpty();
return true; // 数字/布尔等始终视为非空
}
/**
* 深度克隆 JSON 结构
*/
private static Object cloneJson(Object obj) {
return com.alibaba.fastjson.JSON.parse(com.alibaba.fastjson.JSON.toJSONString(obj));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment