package com.common.core.utils;
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.databind.JavaType;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import lombok.extern.slf4j.Slf4j;
|
|
import java.io.IOException;
|
import java.util.Collection;
|
import java.util.List;
|
|
/**
|
* Json转换工具类
|
*/
|
@Slf4j
|
public class JsonUtils {
|
|
public static final ObjectMapper objectMapper = new ObjectMapper();
|
|
/**
|
* 字符串转对象
|
*
|
* @param jsonStr json字符串
|
* @param clazz 转换类型
|
* @param <T>
|
* @return
|
*/
|
public static <T> T string2Object(String jsonStr, Class<T> clazz) throws IOException {
|
return objectMapper.readValue(jsonStr, clazz);
|
}
|
|
/**
|
* 字符串转列表
|
*
|
* @param jsonStr json字符串
|
* @param clazz 类型
|
* @param <T>
|
* @return
|
* @throws JsonProcessingException
|
*/
|
public static <T> Collection<T> string2List(String jsonStr, Class<T> clazz) throws IOException {
|
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Collection.class, clazz);
|
return (Collection<T>) objectMapper.readValue(jsonStr, javaType);
|
}
|
|
/**
|
* 对象转字符串
|
*
|
* @param object 对象
|
* @return
|
* @throws JsonProcessingException
|
*/
|
public static String object2String(Object object) {
|
if (object == null) {
|
return null;
|
}
|
try {
|
return objectMapper.writeValueAsString(object);
|
} catch (JsonProcessingException e) {
|
log.warn("对象转字符串", e);
|
}
|
return null;
|
}
|
|
|
public static String list2String(List object){
|
try {
|
return objectMapper.writeValueAsString(object);
|
} catch (JsonProcessingException e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
}
|