首页 > 解决方案 > 在 Spring Boot 2 中使用自定义 ObjectMapper 返回 ISO-8601 日期

问题描述

我希望我的 s从我的 Spring REST 控制器中LocalDateTime作为 ISO-8601 字符串(例如 )返回。"2020-10-12T10:57:15Z"这以前有效,但现在我使用的是自定义 Jackson2,ObjectMapper这些日期改为作为数组返回:[2020, 10, 12, 10, 57, 15, 200000000]

为什么会发生这种情况?如何自定义ObjectMapper同时仍返回 ISO-8601 日期?

标签: javaspringspring-bootjava-timejackson-databind

解决方案


JacksonAutoConfiguration创建一个关闭ObjectMapper该特性的函数,它以 ISO-8601 字符串形式返回。当您提供自定义时,此默认自动配置将关闭。WRITE_DATES_AS_TIMESTAMPSLocalDateTimesObjectMapper

这可以通过ObjectMapper提供一个Jackson2ObjectMapperBuilderCustomizer. 该 bean 将用于JacksonAutoConfiguration自定义,ObjectMapper同时保持自动配置的行为,例如关闭WRITE_DATES_AS_TIMESTAMPS功能。

@Configuration
public class Config {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer objectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> {
            // Customize the ObjectMapper while maintaining the auto-configuration
        };
    }
}

推荐阅读