一、引入依赖
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-jackson</artifactId>
<version>2.9.0</version>
</dependency>
二、核心代码
public static String obj2JsonString(Object obj) {
if (obj == null) {
return null;
}
try {
ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writeValueAsString(obj);
return result;
} catch (JsonProcessingException e) {
log.error("转换JSON失败:", e);
}
return null;
}
public static Object str2Obj(String input) {
if (StrUtil.isBlank(input)) {
return null;
}
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(input, Object.class);
} catch (JsonProcessingException e) {
log.error("转换JSON失败:", e);
}
return null;
}