模型库
This commit is contained in:
@ -47,4 +47,43 @@ public class JsonUtil {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user