V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
cweijan
V2EX  ›  分享创造

分享一个简单的基于 Jackson 的工具类, 别再用 fastJson 了

  •  
  •   cweijan ·
    cweijan · 2022-05-25 15:54:57 +08:00 · 1004 次点击
    这是一个创建于 713 天前的主题,其中的信息可能已经有所发展或是发生改变。

    又看到有人在讨论 fastjson 的漏洞, 一般用 fastjson 都是为了他相对易用的 API, 但 springboot 项目自带的 jackson 封装下就可以替代 fastjson 了, 分享下我封装的一个基于 jackson 的工具类, 直接复制进去项目就可以用了.

    主要 API:

    • JSON.toJSON(Object obj); // 将对象转为 JSON
    • JSON.parse(String json, Class<T> type); // 将 JSON 转为对象
    • JSON.parseList(String json, Class<T> valueType); // 将 JSON 转为对象 List

    封装 jackson 的意义在于:

    1. jackson 默认不提供工具类, 直接使用需要 new 对象, 有点浪费内存
    2. 对 LocalDateTime 进行支持, 转为通用格式 yyyy-MM-dd HH:mm:ss
    3. 设置 FAIL_ON_UNKNOWN_PROPERTIES 为 false, 这个属性导致反序列化未知属性时会报错, 我想这也是很多人不使用 jackson 的原因.
    import com.fasterxml.jackson.annotation.JsonInclude.Include;
    import com.fasterxml.jackson.core.JsonParser.Feature;
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.JavaType;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.module.SimpleModule;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.StringUtils;
    
    import java.io.IOException;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.LocalTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Collection;
    import java.util.List;
    
    public abstract class JSON {
        private static final ObjectMapper mapper;
        private static final ObjectMapper withEmptyMapper;
        private static final SimpleModule dateModule;
        private static final Logger logger = LoggerFactory.getLogger(JSON.class);
    
        private JSON() {
        }
    
        static {
            //datetime parse
            dateModule = new SimpleModule();
            //配置序列化
            dateModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            dateModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            dateModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
            // 这里还要配置反序列化, 暂时跳过
    //        dateModule.addSerializer(Date.class, new DateSerializer(false, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
            //配置反序列化
            dateModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            dateModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            dateModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
            //without empty
            mapper = new ObjectMapper();
            mapper.setSerializationInclusion(Include.NON_EMPTY);
            buldCommonMapper(mapper);
            //within empty
            withEmptyMapper = new ObjectMapper();
            withEmptyMapper.setSerializationInclusion(Include.ALWAYS);
            buldCommonMapper(withEmptyMapper);
        }
    
        /**
         * 设置 mappepr 的通用属性
         */
        private static void buldCommonMapper(ObjectMapper mapper) {
            mapper.registerModule(dateModule);
            mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
            mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
    
        /**
         * 将对象转换成 json
         *
         * @param originalObject 要转换的对象
         */
        public static String toJSON(Object originalObject) {
    
            if (originalObject == null) return null;
            if (originalObject instanceof String) return String.valueOf(originalObject);
    
            String json = null;
            try {
                json = mapper.writeValueAsString(originalObject);
            } catch (Exception e) {
                logger.error("toJson error:", e);
            }
    
            return json;
        }
    
        /**
         * 将对象转换成 json
         *
         * @param originalObject 要转换的对象
         */
        public static byte[] toJsonByte(Object originalObject) {
    
            if (originalObject == null) return null;
    
            byte[] json = null;
            try {
                json = mapper.writeValueAsBytes(originalObject);
            } catch (Exception e) {
                logger.error("toJson error:", e);
            }
    
            return json;
        }
    
    
        /**
         * 将对象转换成 json,并包含空属性
         *
         * @param originalObject 要转换的对象
         */
        public static String toJsonWithEmpty(Object originalObject) {
    
            if (originalObject == null) return null;
            String json = null;
            try {
                json = withEmptyMapper.writeValueAsString(originalObject);
            } catch (Exception e) {
                logger.error("toJson error:", e);
            }
    
            return json;
        }
    
        /**
         * 进行类型转换
         */
        public static <T> T convert(Object origin, Class<T> targetClass) {
            return mapper.convertValue(origin, targetClass);
        }
    
        /**
         * 将 list 转为另一个 list
         *
         * @param originList  原始 List
         * @param targetClass 目标类型
         * @return 目标类型 List
         */
        public static <O extends Collection<?>, T> List<T> convertList(O originList, Class<T> targetClass) {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(originList.getClass(), targetClass);
            return mapper.convertValue(originList, javaType);
        }
    
    
        /**
         * 根据子 key 获取子 json
         *
         * @param json json 字符串
         * @param key  json 字符串子 key
         * @return 子 json
         */
        public static String get(String json, String key) {
    
            if (StringUtils.isEmpty(json) || StringUtils.isEmpty(key)) return null;
    
            String value;
            try {
                value = mapper.readValue(json, JsonNode.class).get(key).textValue();
            } catch (IOException var5) {
                logger.info(var5.getMessage());
                value = null;
            }
    
            return value;
        }
    
        /**
         * 将 json 转成 List
         *
         * @param json      json 字符串
         * @param valueType list 泛型
         */
        public static <T> List<T> parseList(String json, Class<T> valueType) {
    
            return (List<T>) parseCollection(json, List.class, valueType);
        }
    
        /**
         * 将 json 转成 List
         *
         * @param json      json 字符串
         * @param valueType list 泛型
         */
        public static <T, E extends Collection> Collection<T> parseCollection(String json, Class<E> collectionClass, Class<T> valueType) {
    
            if (StringUtils.isEmpty(json) || valueType == null) return null;
    
            JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, valueType);
    
            Collection<T> objectList;
            try {
                objectList = mapper.readValue(json, javaType);
            } catch (Exception e) {
                logger.error("parseList error:" + e.getMessage(), e);
                objectList = null;
            }
    
            return objectList;
        }
    
        /**
         * 将 json 转成指定的类对象
         */
        @SuppressWarnings("unchecked")
        public static <T> T parse(Object obj, Class<T> type) {
    
            if (StringUtils.isEmpty(obj) || type == null) return null;
            if (type == String.class) return (T) obj;
    
            T result;
            try {
                result = mapper.readValue(toJSON(obj), type);
            } catch (Exception e) {
                logger.error("parse error:" + e.getMessage(), e);
                result = null;
            }
    
            return result;
        }
    
        public static SimpleModule getDateModule() {
            return dateModule;
        }
    }
    
    
    cweijan
        1
    cweijan  
    OP
       2022-05-25 15:58:25 +08:00
    @Livid 我的账号是废了吗
    thetbw
        2
    thetbw  
       2022-09-24 17:11:16 +08:00
    赞一个
    thetbw
        3
    thetbw  
       2022-09-24 17:16:58 +08:00
    不过 parse 那个方法写的有问题吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1067 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:08 · PVG 06:08 · LAX 15:08 · JFK 18:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.