在Spring Boot 2中使用自定义ObjectMapper返回ISO-8601日期

问题描述

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

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

解决方法

JacksonAutoConfiguration创建一个ObjectMapper功能处于关闭状态的WRITE_DATES_AS_TIMESTAMPS,它返回LocalDateTimes作为ISO-8601字符串。当您提供自定义ObjectMapper时,此默认自动配置将关闭。

可以通过提供ObjectMapper而不是提供自定义Jackson2ObjectMapperBuilderCustomizer来解决。 JacksonAutoConfiguration将使用该bean来自定义ObjectMapper,同时保持自动配置的行为,例如关闭WRITE_DATES_AS_TIMESTAMPS功能。

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