Files
yjearth/src/main/java/com/yj/earth/common/util/JsonUtil.java
2025-09-26 13:46:24 +08:00

136 lines
3.9 KiB
Java

package com.yj.earth.common.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
/**
* Map与JSON互相转换工具类
*/
@Slf4j
public class JsonUtil {
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* 将 Map 转换为 JSON 字符串
*/
public static String mapToJson(Map<String, Object> map) {
if (map == null || map.isEmpty()) {
return "{}";
}
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
log.error("Map转JSON失败", e);
return null;
}
}
/**
* 将 JSON 字符串转换为 Map
*/
public static Map<String, Object> jsonToMap(String json) {
if (json == null || json.trim().isEmpty()) {
return new HashMap<>(0);
}
try {
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
} catch (Exception e) {
log.error("JSON转Map失败、JSON内容: {}", json, e);
return new HashMap<>(0);
}
}
/**
* 将 JSON 字符串转换为指定类型的对象
*/
public static <T> T jsonToObject(String json, Class<T> clazz) {
if (json == null || json.trim().isEmpty()) {
return null;
}
return objectMapper.convertValue(json, clazz);
}
/**
* 将 Map 转换为指定类型的对象
*/
public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
if (map == null || clazz == null) {
return null;
}
try {
// 使用 ObjectMapper 将 Map 转换为指定类型对象
return objectMapper.convertValue(map, clazz);
} catch (IllegalArgumentException e) {
log.error("Map转对象失败、目标类型: {}, Map内容: {}", clazz.getName(), map, e);
return null;
}
}
/**
* 将任意 Object 转化为 JSON
*/
public static String toJson(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.error("对象转JSON失败", e);
return null;
}
}
/**
* 修改JSON字符串中指定键的值
*/
public static String modifyJsonValue(String json, String key, Object value) {
if (json == null || json.trim().isEmpty() || key == null || key.trim().isEmpty()) {
return json;
}
// 将JSON转换为Map
Map<String, Object> map = jsonToMap(json);
if (map == null) {
return json;
}
// 解析键、支持嵌套
String[] keyParts = key.split("\\.");
Map<String, Object> currentMap = map;
// 遍历键的各个部分、处理嵌套结构
for (int i = 0; i < keyParts.length; i++) {
String part = keyParts[i];
// 如果是最后一个部分、直接设置值
if (i == keyParts.length - 1) {
currentMap.put(part, value);
break;
}
// 如果不是最后一个部分、检查是否存在该键且对应的值是Map
Object nextObj = currentMap.get(part);
if (nextObj instanceof Map) {
currentMap = (Map<String, Object>) nextObj;
} else {
// 如果不存在或不是 Map、创建新的 Map
Map<String, Object> newMap = new HashMap<>();
currentMap.put(part, newMap);
currentMap = newMap;
}
}
// 将修改后的 Map 转换回 JSON
String result = mapToJson(map);
return result != null ? result : json;
}
}