SpringBoot LocalDateTime序列化配置

2022-08-17 14:57:32 浏览数 (3)

项目中用LocalDateTime替换Date后, 许多地方需要增加配置

配置Json响应格式化方式

注册JavaTimeModule

代码语言:javascript复制
/**
 * 序列化LocalDateTime
 */
@Bean
public JavaTimeModule javaTimeModule() {
    JavaTimeModule module = new JavaTimeModule();
    DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(pattern));
    module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(pattern));
    return module;
}
代码语言:javascript复制
/**
 * 配置web序列化方式
 *
 * @param javaTimeModule javaTimeModule
 */
@Bean("objectMapperForWebMessageConverter")
@Primary
public ObjectMapper objectMapperForWebConvert(JavaTimeModule javaTimeModule) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.registerModule(javaTimeModule);
    return objectMapper;
}

WebMvcConfig

代码语言:javascript复制
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

    private final ObjectMapper objectMapper;


    public WebMvcConfig(@Qualifier("objectMapperForWebMessageConverter") ObjectMapper diObjectMapper) {
        objectMapper = diObjectMapper;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

        converter.setObjectMapper(objectMapper);
        converters.add(0, stringHttpMessageConverter);
        converters.add(1, converter);
    }
}
配置Redis Value序列化方式

重新注册一个ObjectMapper

代码语言:javascript复制
    @Bean("objectMapperForRedisSerializer")
    public ObjectMapper objectMapperForRedisSerializer(JavaTimeModule javaTimeModule) {
        var om = new ObjectMapper();
        om.registerModule(new SimpleModule().addSerializer(new NullValueSerializer(null)));
        om.registerModule(javaTimeModule);
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.EVERYTHING,
                JsonTypeInfo.As.PROPERTY);
        return om;
    }
    
    static class NullValueSerializer extends StdSerializer<NullValue> {

        @Serial
        private static final long serialVersionUID = 1999052150548658808L;

        private final String classIdentifier;

        /**
         * @param classIdentifier can be {@literal null} and will be defaulted to {@code @class}.
         */
        NullValueSerializer(@Nullable String classIdentifier) {
            super(NullValue.class);
            this.classIdentifier = StringUtils.hasText(classIdentifier) ? classIdentifier : "@class";
        }

        @Override
        public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException {
            jgen.writeStartObject();
            jgen.writeStringField(classIdentifier, NullValue.class.getName());
            jgen.writeEndObject();
        }

        @Override
        public void serializeWithType(NullValue value, JsonGenerator gen, SerializerProvider serializers,
                                      TypeSerializer typeSer) throws IOException {
            serialize(value, gen, serializers);
        }
    }
代码语言:javascript复制
    @Bean("redisTemplateForObjectValue")
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory,
                                                       @Qualifier("objectMapperForRedisSerializer") ObjectMapper om) {
        var redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        //key序列化方式
        var stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        //value序列化方式
        var jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(om);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.setEnableTransactionSupport(false);
        return redisTemplate;
    }

0 人点赞