import java.io.IOException;
import java.io.StringWriter;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Jackson 对象与json互转工具类
*/
public class JacksonUtil {
private static ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
public static final Logger LOGGER = LoggerFactory.getLogger(JacksonUtil.class);
public static String beanToJson(Object obj) {
StringWriter sw = new StringWriter();
try{
JsonGenerator gen = new JsonFactory().createGenerator(sw);
mapper.writeValue(gen, obj);
gen.close();
} catch (IOException e) {
LOGGER.error("bean = {} to json error = {} !", obj, e);
e.printStackTrace();
}
return sw.toString();
}
public static <T> T jsonToBean(String jsonStr, Class<T> objClass) {
try{
return mapper.readValue(jsonStr, objClass);
} catch (IOException e) {
LOGGER.error("json = {} to objClass = {} error = {} !", jsonStr, objClass, e);
e.printStackTrace();
}
return null;
}
public static <T> T jsonToBean(String jsonStr, JavaType javaType) {
try{
return (T) mapper.readValue(jsonStr, javaType);
} catch (IOException e) {
LOGGER.error("json = {} to javaType = {} error = {} !", jsonStr, javaType, e);
e.printStackTrace();
}
return null;
}
public static <T> T jsonToBean(String jsonStr, TypeReference valueTypeRef) {
try {
return mapper.readValue(jsonStr, valueTypeRef);
} catch (IOException e) {
LOGGER.error("json = {} to objClass = {} error = {} !", jsonStr, valueTypeRef.getClass(), e);
e.printStackTrace();
}
return null;
}
public static String writeValueAsString(Object bean) {
try {
return mapper.writeValueAsString(bean);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
json转bean
最新推荐文章于 2024-07-29 03:32:52 发布
该文章提供了一个名为JacksonUtil的Java类,该类利用Jackson库进行对象到JSON及JSON到对象的转换。类中包含多个静态方法,如beanToJson、jsonToBean,支持不同类型转换并处理异常情况。
摘要由CSDN通过智能技术生成