定制LocalDateTime序列,把序列化格式

SpringBoot版本:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

问题描述:
  项目使用LocalDateTime作为日期类型,默认下,前端传参,后端返回的字符串形式如:2016-10-20T11:08:46
现在要求:
  对应的日期字符串格式如下:2016-10-20 11:08:46,即将 T 删除

解决方案:
  SpringBoot中使用Jackson2ObjectMapperBuilderCustomizer作为序列化,反序列化器,通过配置该类可以定制时期格式
代码如下:
@Configuration
public class LocalDateTimeSerializerConfig {
    @org.springframework.beans.factory.annotation.Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer())
                .serializerByType(LocalDateTime.class, localDateTimeSerializer());
    }
}

 

定制LocalDateTime序列,把序列化格式

上一篇:React ant-design-pro 运行报错


下一篇:搬运 RGB格式是个啥