使用Jaskon进行序列化和反序列化

在项目中用Jackson完成json和对象之间的转换,可以完成把对象序列化之后,存入redis,设置超时间,完成用户的登陆。

1. 在maven的pom文件中引入jackson.jar

    
      org.codehaus.jackson
      jackson-mapper-asl
      1.9.12
    

2. 封装一个单独的JsonUtil类,提高可用性

@Slf4j
public class JsonUtil {
    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(DateTimeUtil.STANDARD_FORMAT));
        //忽略在json字符串中存在,在java属性中不存在的情况。防止错误
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

// 把对象转化为json字符串
    public static  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;
        }
    }


    // 返回格式化之后的字符串
    public static  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;
        }
    }


    public  static   T string2Obj(String str,Class clazz){
        if (StringUtils.isEmpty(str)||clazz ==null){
            return  null;
        }
        try {

            return  clazz.equals(String.class)?(T)str:objectMapper.readValue(str,clazz);
        }catch (Exception e){
            log.warn("Parse str to object error",e);
            return  null;
        }

    }

    public  static   T string2Obj(String str, TypeReference reference){
        if (StringUtils.isEmpty(str)||reference ==null){
            return  null;
        }
        try {

            return (T) (reference.getType().equals(String.class)?(T)str:objectMapper.readValue(str,reference));
        }catch (Exception e){
            log.warn("Parse str to object error",e);
            return  null;
        }

    }


    public  static   T string2Obj(String str,Class collectionClass,Class...elecmentClassess){
        JavaType javatype= objectMapper.getTypeFactory().constructParametricType(collectionClass,elecmentClassess);
        try {

            return  objectMapper.readValue(str,javatype);
        }catch (Exception e){
            log.warn("Parse str to object error",e);
            return  null;
        }

    }

}

你可能感兴趣的:(java,json,jackxon)