import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.senyint.cloudhis.common.core.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* @author Alen
* @date 2021-09-15 15:19
* @since 2021-09-15 15:19
*/
public class JsonUtils {
private static ObjectMapper objectMapper;
private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
protected static ObjectMapper getObjectMapper(){
if(objectMapper == null){
objectMapper = SpringUtils.getBeanByType(ObjectMapper.class);
}
return objectMapper;
}
/**
* 对象转换成json串
* @param o
* @return
* @throws JsonProcessingException
*/
public static String toJsonString(Object o) throws JsonProcessingException {
ObjectMapper objectMapper = getObjectMapper();
if(ObjectUtils.isNotNull(objectMapper)){
String resultJson=objectMapper.writeValueAsString(o);
logger.debug("传入方法 toJsonString : {}",resultJson);
return resultJson;
}
return "";
}
/**
* json串转换成对象
* @param json
* @param tClass
* @param <T>
* @return
* @throws IOException
*/
public static <T> T toJsonObject(String json,Class<T> tClass,Class ... clazz) throws IOException {
ObjectMapper objectMapper = getObjectMapper();
if(ObjectUtils.isNotNull(objectMapper)){
if(ArrayUtils.isNotEmpty(clazz)){
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(tClass,clazz);
T obj = objectMapper.readValue(json, javaType);
logger.debug("返回参数方法toJsonObject; {}",obj);
return obj ;
}else {
T obj= objectMapper.readValue(json,tClass);
logger.debug("返回参数方法toJsonObject; {}",obj);
return obj;
}
}
return null;
}
}
JsonUtils工具类实体和json字符串互转
最新推荐文章于 2024-07-26 03:07:25 发布