基于Jackson实现对象的序列化和反序列化工具
2019-10-14 本文已影响0人
Roct
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
// 将对象和Json相互转换
public class JsonUtil {
private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static ObjectMapper objectMapper = new ObjectMapper();
static {
// 对象的所有字段全部列入
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS);
// 取消默认转换timestamps对象
objectMapper.configure(SerializationConfig.Feature
.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
// 忽略空Bean转json的错误
objectMapper.configure(SerializationConfig.Feature
.FAIL_ON_EMPTY_BEANS, false);
// 所有日期统一格式
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 忽略 在json字符串中存在, 但是在java对象中不存在对应属性的情况, 防止出错
objectMapper.configure(DeserializationConfig.Feature
.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static <T> String obj2String(T obj) {
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper
.writeValueAsString
(obj);
} catch (Exception e) {
logger.error("Parse object to String error:" + e);
return null;
}
}
/**
* 返回一个格式化好的字符串, 用于调试
* @param obj
* @param <T>
* @return
*/
public static <T> String obj2StringPretty(T obj) {
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString
(obj);
} catch (Exception e) {
logger.error("Parse object to String error:" + e);
return null;
}
}
/**
* 将字符串转成对象, 单个
* @param str
* @param clazz
* @param <T>
* @return
*/
public static <T> T string2Obj(String str, Class<T> clazz) {
if (StringUtils.isEmpty(str) || clazz == null) {
return null;
}
try {
return clazz.equals(String.class) ? (T)str : objectMapper.readValue
(str, clazz);
} catch (IOException e) {
logger.error("Parse String to Object error :" + e);
return null;
}
}
/**
* 将字符串转换成对象, 数组
* @param str
* @param typeReference
* @param <T>
* @return
*/
public static <T> T string2Obj(String str, TypeReference<T> typeReference) {
if (StringUtils.isEmpty(str) || typeReference == null) {
return null;
}
try {
return (T)(typeReference.getType().equals(String.class) ? (T)str :
objectMapper.readValue
(str, typeReference));
} catch (IOException e) {
logger.error("Parse String to typeReference Object error :" + e);
return null;
}
}
/**
* 将字符串转换成对象, 数组
* @param str
* @param typeReference
* @param <T>
* @return
*/
public static <T> T string2Obj(String str, Class<?> collectionClass,
Class<?>... elementClasses) {
JavaType javaType = objectMapper.getTypeFactory()
.constructParametricType(collectionClass, elementClasses);
try {
return objectMapper.readValue(str, javaType);
} catch (IOException e) {
logger.error("Parse String to Object2 error :" + e);
return null;
}
}
/**
* 测试代码
*/
public static void main(String[] args) {
User user1 = new User();
user1.setId(209);
user1.setPassword("dhjskhsjdhj");
user1.setAnswer("ccccccccc");
User user2 = new User();
user2.setId(300);
user2.setPassword("300wwwwww");
user2.setAnswer("300wwwwwweeeeeeeeee");
List list = new ArrayList();
list.add(user1);
list.add(user2);
String str = obj2String(list);
System.out.println("strL:::::" + str);
List<User> userList = string2Obj(str, new TypeReference<List<User>>()
{});
List<User> userList2 = string2Obj(str, List.class, User.class);
System.out.println("end");
}
}