zoukankan      html  css  js  c++  java
  • Java jackson配置类,Java jackson工具类,SpringBoot Jackson类配置

    Java jackson配置类,Java jackson工具类,SpringBoot Jackson类配置

    ================================

    ©Copyright 蕃薯耀 2021-04-27

    https://www.cnblogs.com/fanshuyao/

    一、SpringBoot Jackson类配置

    SpringBoot 配置ObjectMapper的bean对象,通过增加@ResponseBody返回json对象

    使用配置类返回ObjectMapper,而不是在配置文件,可以让ObjectMapper是同一个,不用在jsonUtils再声明一个,导致两处地方可能存在不一致的地方。在jsonUtils直接注入ObjectMapper,保持一致。

    import java.text.SimpleDateFormat;
    import java.util.TimeZone;
    
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
    
    import com.fasterxml.jackson.annotation.JsonInclude.Include;
    import com.fasterxml.jackson.core.JsonParser.Feature;
    import com.fasterxml.jackson.core.json.JsonReadFeature;
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    
    @Configuration
    public class JacksonConfig {
    
        @Bean("objectMapper")
        @Primary
        @ConditionalOnMissingBean(ObjectMapper.class)
        public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder) {
            
            ObjectMapper mapper = builder.build();
            
            // 日期格式
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            
            //GMT+8
            //map.put("CTT", "Asia/Shanghai");
            mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            
            // Include.NON_NULL 属性为NULL 不序列化
            //ALWAYS // 默认策略,任何情况都执行序列化
            //NON_EMPTY // null、集合数组等没有内容、空字符串等,都不会被序列化
            //NON_DEFAULT // 如果字段是默认值,就不会被序列化
            //NON_ABSENT // null的不会序列化,但如果类型是AtomicReference,依然会被序列化
            mapper.setSerializationInclusion(Include.NON_NULL);
            
            //允许字段名没有引号(可以进一步减小json体积):
            mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            
            //允许单引号:
            mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
            
            // 允许出现特殊字符和转义符
            //mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);这个已经过时。
            mapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
            
            //允许C和C++样式注释:
            mapper.configure(Feature.ALLOW_COMMENTS, true);
    
            //序列化结果格式化,美化输出
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            
            //枚举输出成字符串
            //WRITE_ENUMS_USING_INDEX:输出索引
            mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
            
            //空对象不要抛出异常:
            mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
            
            //Date、Calendar等序列化为时间格式的字符串(如果不执行以下设置,就会序列化成时间戳格式):
            mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            
            //反序列化时,遇到未知属性不要抛出异常:
            mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            
            //反序列化时,遇到忽略属性不要抛出异常:
            mapper.disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
            
            //反序列化时,空字符串对于的实例属性为null:
            mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
            
            return mapper;
        }
        
    }

    二、Java jackson工具类

    ObjectMapper从JacksonConfig配置类注入,使用同一个ObjectMapper

    import java.io.IOException;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.JavaType;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    /**
     * Jackson工具类
     **/
    @Component
    @ConditionalOnClass(JacksonConfig.class)
    public class JsonUtil { private static Logger log = Logger.getLogger(JsonUtil.class); public static ObjectMapper objectMapper; public static ObjectMapper getObjectMapper() { return objectMapper; } //静态变量注入时,@Autowired注解只能在方法,不能在参数 @Autowired public void setObjectMapper(ObjectMapper objectMapper) { JsonUtil.objectMapper = objectMapper; } /** * Object转json字符串 */ public static <T> String toJson(T obj) { try { if (obj == null) { return null; }else if (obj instanceof String) { return (String) obj; }else { return objectMapper.writeValueAsString(obj); } } catch (Exception e) { log.error("Parse object to String error", e); return null; } } /** * Object转json字符串并格式化美化 */ public static <T> String toJsonPretty(T obj) { try { if (obj == null) return null; else if (obj instanceof String) return (String) obj; else return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (Exception e) { log.error("Parse object to String Pretty error", e); return null; } } /** * json转object */ @SuppressWarnings("unchecked") public static <T> T toBean(String json, Class<T> clazz) { try { if (StringUtils.isEmpty(json) || clazz == null) { return null; }else if(clazz.equals(String.class)){ return (T)json; }else{ return objectMapper.readValue(json, clazz); } } catch (IOException e) { log.error("Parse String to bean error", e); return null; } } /** * json转集合 * @param <T> * @param json * @param typeReference * <li>new TypeReference<List<User>>() {}</li> * @return */ @SuppressWarnings("unchecked") public static <T> T toBean(String json, TypeReference<T> typeReference) { try { if (StringUtils.isEmpty(json) || typeReference == null) { return null; } else if (typeReference.getType().equals(String.class)) { return (T) json; } else { return objectMapper.readValue(json, typeReference); } } catch (IOException e) { log.error("Parse String to Bean error", e); return null; } } /** * string转object 用于转为集合对象 * @param json Json字符串 * @param collectionClass 被转集合的类 * <p>List.class</p> * @param elementClasses 被转集合中对象类型的类 * <p>User.class</p> */ public static <T> T toBean(String json, Class<?> collectionClass, Class<?>... elementClasses) { try { JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); return objectMapper.readValue(json, javaType); } catch (IOException e) { log.error("Parse String to Bean error", e); return null; } } }

    三、application.properties文件配置jackson返回(使用类配置的方式,可以省略这个)

    org.springframework.boot.autoconfigure.jackson.JacksonProperties

    #jackson
    #日期格式化
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    #时区
    spring.jackson.time-zone=GMT+8
    #格式化输出 
    spring.jackson.serialization.indent-output=true
    #忽略无法转换的对象
    spring.jackson.serialization.fail-on-empty-beans=false
    #设置空如何序列化
    spring.jackson.defaultPropertyInclusion=NON_NULL
    #允许对象忽略json中不存在的属性
    spring.jackson.deserialization.fail-on-unknown-properties=false
    #允许出现特殊字符和转义符
    spring.jackson.parser.allow-unquoted-control-chars=true
    #允许出现单引号
    spring.jackson.parser.allow-single-quotes=true

    jackson自动装配类

    org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration

        @Configuration(proxyBeanMethods = false)
        @ConditionalOnClass(Jackson2ObjectMapperBuilder.class)
        static class JacksonObjectMapperConfiguration {
    
            @Bean
            @Primary
            @ConditionalOnMissingBean
            ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
                return builder.createXmlMapper(false).build();
            }
    
        }

    理论上,也可以在配置文件配置jackson,然后从spring容器获取ObjectMapper,在jackson工具类注入该对象,保证使用同一个ObjectMapper对象。

    代码如下:

    /**
     * Jackson工具类
     *
     **/
    @Component
    @ConditionalOnBean(name = "jacksonObjectMapper")
    public class JsonUtil {
    
        //自定义的静态变量objectMapper
        private static ObjectMapper objectMapper;
        
        public static ObjectMapper getObjectMapper() {
            return objectMapper;
        }
    
        /**
         * 先在application.properties配置好jackson的,然后将jacksonObjectMapper注入到自定义的变量objectMapper
         * @param jacksonObjectMapper
         */
        @Autowired
        public void setObjectMapper(ObjectMapper jacksonObjectMapper) {
            JsonUtil.objectMapper = jacksonObjectMapper;
        }
    
        
    }

    (时间宝贵,分享不易,捐赠回馈,^_^)

    ================================

    ©Copyright 蕃薯耀 2021-04-27

    https://www.cnblogs.com/fanshuyao/

    今天越懒,明天要做的事越多。
  • 相关阅读:
    Linux pmap 工具
    bzoj 1060 贪心
    bzoj 1076 状压DP
    bzoj 1150 贪心
    bzoj 1412 最小割 网络流
    bzoj 3212 线段树
    bzoj 1942 斜率优化DP
    bzoj 1876 高精
    bzoj 1880 最短路
    斜率优化DP讲解
  • 原文地址:https://www.cnblogs.com/fanshuyao/p/14707710.html
Copyright © 2011-2022 走看看