进一步优化 json 工具类,默认使用 Spring 初始化出来的

This commit is contained in:
YunaiV
2021-01-24 12:37:58 +08:00
parent eadc4f749a
commit fa3f382210
10 changed files with 59 additions and 38 deletions

View File

@@ -1,25 +1,33 @@
package cn.iocoder.dashboard.util.json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Set;
/**
* JSON 工具类
*
* @author 芋道源码
*/
public class JSONUtils {
public class JsonUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
// TODO 芋艿需要将 Spring 的设置下进来
public static void setObjectMapper(ObjectMapper objectMapper) {
JSONUtils.objectMapper = objectMapper;
/**
* 初始化 objectMapper 属性
*
* 通过这样的方式使用 Spring 创建的 ObjectMapper Bean
*
* @param objectMapper ObjectMapper 对象
*/
public static void init(ObjectMapper objectMapper) {
JsonUtils.objectMapper = objectMapper;
}
public static String toJSONString(Object object) {
public static String toJsonString(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
@@ -43,4 +51,12 @@ public class JSONUtils {
}
}
public static Object parseObject(String text, TypeReference<Set<Long>> typeReference) {
try {
return objectMapper.readValue(text, typeReference);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -2,7 +2,7 @@ package cn.iocoder.dashboard.util.servlet;
import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.iocoder.dashboard.util.json.JSONUtils;
import cn.iocoder.dashboard.util.json.JsonUtils;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
@@ -28,7 +28,7 @@ public class ServletUtils {
*/
@SuppressWarnings("deprecation") // 必须使用 APPLICATION_JSON_UTF8_VALUE否则会乱码
public static void writeJSON(HttpServletResponse response, Object object) {
String content = JSONUtils.toJSONString(object);
String content = JsonUtils.toJsonString(object);
ServletUtil.write(response, content, MediaType.APPLICATION_JSON_UTF8_VALUE);
}