ShiShiYiBan/src/main/java/cn/iocoder/dashboard/util/json/JsonUtils.java

79 lines
2.1 KiB
Java
Raw Normal View History

2021-01-17 00:28:56 +08:00
package cn.iocoder.dashboard.util.json;
2021-01-26 01:29:03 +08:00
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
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;
2021-01-17 00:28:56 +08:00
/**
* JSON 工具类
*
* @author 芋道源码
*/
public class JsonUtils {
2021-01-17 00:28:56 +08:00
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* 初始化 objectMapper 属性
2021-03-08 09:15:52 +08:00
* <p>
* 通过这样的方式使用 Spring 创建的 ObjectMapper Bean
*
* @param objectMapper ObjectMapper 对象
*/
public static void init(ObjectMapper objectMapper) {
JsonUtils.objectMapper = objectMapper;
}
public static String toJsonString(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, Class<T> clazz) {
2021-01-26 01:29:03 +08:00
if (StrUtil.isEmpty(text)) {
return null;
}
try {
return objectMapper.readValue(text, clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
2021-01-26 01:29:03 +08:00
if (ArrayUtil.isEmpty(bytes)) {
return null;
}
try {
return objectMapper.readValue(bytes, clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
2021-01-17 00:28:56 +08:00
public static Object parseObject(String text, TypeReference<Set<Long>> typeReference) {
try {
return objectMapper.readValue(text, typeReference);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
2021-03-08 09:15:52 +08:00
public static <T> T parseByType(String text, TypeReference<T> typeReference) {
try {
return objectMapper.readValue(text, typeReference);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
2021-01-17 00:28:56 +08:00
}