Jackson 统一配置 日期转换格式

2023-10-15 09:27:53 浏览数 (2)

 1.配置文件中进行修改

代码语言:javascript复制
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss

这样序列化后,Date类型会被格式化成配置中的格式。

2.配置类中配置

创建JacksonConfig.java

代码语言:javascript复制
@Configuration
public class JacksonConfig {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public Jackson2ObjectMapperBuilderCustomizer customJackson() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder builder) {
                builder.serializerByType(LocalDateTime.class,
                        new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                builder.serializerByType(LocalDate.class,
                        new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                builder.serializerByType(LocalTime.class,
                        new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                builder.deserializerByType(LocalDateTime.class,
                        new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                builder.deserializerByType(LocalDate.class,
                        new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                builder.deserializerByType(LocalTime.class,
                        new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                builder.serializationInclusion(JsonInclude.Include.NON_NULL);
                builder.failOnUnknownProperties(false);
                builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            }
        };
    }
}

1、Springboot默认使用的json解析框架是jackson框架 2、jackson解析框架在解析实体类里面是Date数据类型的数据时的默认格式是:UTC类型,即yyyy-MM-dd’T’HH:mm:ss.SSS 并且默认为 8时区,即时间基础上加8小时 请求数据格式为: 'yyyy-MM-dd HH:mm:ss',但是在接收到数据的时候,需要通过jackson把数据转化成Dto对象。jackson转化的时候,默认的时间格式是 'yyyy-MM-dd'T'HH:mm:ss.SSS’,

0 人点赞