update 优化日志参数字段排除处理 采用更好的JsonNode节点树处理 性能更好 避免报错
This commit is contained in:
+42
@@ -10,6 +10,7 @@ import org.dromara.common.core.utils.StringUtils;
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -142,6 +143,47 @@ public class JsonUtils {
|
||||
return JSON_MAPPER.readValue(text, JSON_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象转换为 JSON 字符串,并递归移除指定字段。
|
||||
*
|
||||
* @param object 要转换的对象
|
||||
* @param fieldNames 需要移除的字段名
|
||||
* @return 移除字段后的 JSON 字符串
|
||||
*/
|
||||
public static String toJsonStringExcludeFields(Object object, String... fieldNames) {
|
||||
if (ObjectUtil.isNull(object)) {
|
||||
return null;
|
||||
}
|
||||
JsonNode node = JSON_MAPPER.valueToTree(object);
|
||||
removeFields(node, fieldNames);
|
||||
return toJsonString(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 JSON 树中递归移除指定字段。
|
||||
*
|
||||
* @param node JSON 节点
|
||||
* @param fieldNames 需要移除的字段名
|
||||
* @return 原 JSON 节点
|
||||
*/
|
||||
public static JsonNode removeFields(JsonNode node, String... fieldNames) {
|
||||
if (node == null || ArrayUtil.isEmpty(fieldNames)) {
|
||||
return node;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
ObjectNode objectNode = (ObjectNode) node;
|
||||
for (String fieldName : fieldNames) {
|
||||
if (StringUtils.isNotBlank(fieldName)) {
|
||||
objectNode.remove(fieldName);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (JsonNode child : node) {
|
||||
removeFields(child, fieldNames);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串是否为合法 JSON(对象或数组)
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user