zoukankan      html  css  js  c++  java
  • 用来进行序列化和反序列化的工具类

    package com.*******.****.drp.util;
    import java.io.IOException;
     
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.JsonParseException;
    import org.codehaus.jackson.JsonParser;
    import org.codehaus.jackson.map.DeserializationConfig;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
     
    import lombok.extern.slf4j.Slf4j;
    /** 
    * @Description:
    * @author :******| paranoia_zk@yeah.net 
    * @date :2017年6月8日 上午10:32:04 
    */
    @Slf4j
    public class JacksonUtil {
        private final static ObjectMapper objectMapper = new ObjectMapper();
     
        static {
            objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            objectMapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true);
            objectMapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true);
            objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
     
        public static String encode(Object obj) {
            try {
                return objectMapper.writeValueAsString(obj);
            } catch (JsonGenerationException e) {
                log.error("encode(Object)", e); //$NON-NLS-1$
            } catch (JsonMappingException e) {
                log.error("encode(Object)", e); //$NON-NLS-1$
            } catch (IOException e) {
                log.error("encode(Object)", e); //$NON-NLS-1$
            }
            return null;
        }
     
        /**
         * 将json string反序列化成对象
         *
         * @param json
         * @param valueType
         * @return
         */
        public static <T> T decode(String json, Class<T> valueType) {
            try {
                return objectMapper.readValue(json, valueType);
            } catch (JsonParseException e) {
                log.error("decode(String, Class<T>)", e);
            } catch (JsonMappingException e) {
                log.error("decode(String, Class<T>)", e);
            } catch (IOException e) {
                log.error("decode(String, Class<T>)", e);
            }
            return null;
        }
     
    }
  • 相关阅读:
    url参数中出现+、空格、=、%、&、#等字符的解决办法
    hybrid app、react-native 区别
    native app、web app、hybrid app、react-native 区别
    hybrid app 知识点
    使用过的bug跟踪系统
    移动端点击延迟的解决方案
    Java中的null
    类加载器 知识点
    hashcode 知识点
    stylus 知识点
  • 原文地址:https://www.cnblogs.com/qingmuchuanqi48/p/13326603.html
Copyright © 2011-2022 走看看