序列化和反序列化工具类
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
package com.mark.util;
import com.google.common.collect.Lists;
import com.mark.pojo.User;
import lombok.extern.slf4j.Slf4j;
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 java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* Created by Mark on 2018/4/20.
* Json序列化工具类
*/
@Slf4j
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
//对象的所有字段全部列入
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS);
//取消默认转换timestamps形式
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
//忽略空Bean转json的错误
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
//所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss
objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));
//反序列化属性:忽略在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
}
//1.对象转为字符串
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) {
log.warn("Parse Object to String error",e);
return null;
}
}
//2.对象装字符串2【带有格式】
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) {
log.warn("Parse Object to String error",e);
return null;
}
}
//3.字符串反序列话为普通对象
public static <T> T string2Obj(String str,Class<T> clazz){
if(StringUtils.isEmpty(str) || clazz == null){
return null;
}
try {
//如果需要转为String类型就直接返回,否则才进行转换
return clazz.equals(String.class) ? (T) str :objectMapper.readValue(str,clazz);
} catch (IOException e) {
log.warn("Parse String to Object error",e);
return null;
}
}
//字符串反序列化为集合1
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)? str : objectMapper.readValue(str,typeReference));
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
//字符串反序列化为集合2
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 (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
//测试
public static void main(String[] args) {
/* User user1 = new User();
user1.setId(1);
user1.setUsername("mark");
String user1Json = JsonUtil.obj2String(user1);//对象序列化
String user1JsonPretty = JsonUtil.obj2StringPretty(user1);//对象序列化
System.out.println(user1Json);
System.out.println(user1JsonPretty);
User user = JsonUtil.string2Obj(user1Json,User.class);
System.out.println(user.getId());*/
User user1 = new User();
user1.setId(1);
user1.setUsername("mark");
User user2 = new User();
user2.setId(1);
user2.setUsername("mark");
List<User> userList = Lists.newArrayList();
userList.add(user1);
userList.add(user2);
String result = JsonUtil.obj2StringPretty(userList);//集合序列化为字符串
System.out.println(result);
List<User> userList1 = JsonUtil.string2Obj(result, new TypeReference<List<User>>() {
});
List<User> userList2 = JsonUtil.string2Obj(result,List.class,User.class);
System.out.println("end");
}
}