对象映射器:指定序列化和反序列化时数据映射格式(Long类型反序列化与指定日期格式类型)

360 阅读1分钟
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
   
    /**
     * 扩展mvc框架的消息转换器
     *
     * @param converters 转换器列表集合
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        // 设置自定义的对象映射器
        messageConverter.setObjectMapper(new OptimizationObjectMapper());
        // 通过设置索引,让自己的转换器放在最前面,否则默认的jackson转换器会在前面,用不上自己配置的转换器
        converters.add(0, messageConverter);
    }


    /**
     * 定义成员内部类,实现该功能
     *
     * 对象映射器:指定序列化和反序列化时数据映射格式。
     * 本对象映射器继承自Jackson中提供的转换核心映射器ObjectMapper
     * 支持
     * 指定格式的日期时间字符串与LocalDateTime的序列化和反序列化
     * BigInteger、Long --> String的序列化
     */
    class OptimizationObjectMapper extends ObjectMapper {
        public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
        public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

        public OptimizationObjectMapper() {
            super();
            // 反序列化特性:反序列化时属性不存在的兼容处理,未知属性时不报异常
            this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
            this.getDeserializationConfig().withoutFeatures(FAIL_ON_UNKNOWN_PROPERTIES);

            // 新建功能模块,并添加序列化器和反序列化器
            SimpleModule simpleModule = new SimpleModule()
                    // 添加指定规则的反序列化器
                    .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                    .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                    .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))

                    // 添加指定规则的序列化器
                    .addSerializer(BigInteger.class, ToStringSerializer.instance)
                    // Long --> String,可以解决本案中的问题
                    .addSerializer(Long.class, ToStringSerializer.instance)

                    .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                    .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                    .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
            //注册功能模块
            this.registerModule(simpleModule);
        }
    }

}