Search code examples
javaspringspring-bootjava-timejackson-databind

Return ISO-8601 dates with custom ObjectMapper in Spring Boot 2


I want my LocalDateTimes to be returned as ISO-8601 strings (e.g. "2020-10-12T10:57:15Z") from my Spring REST Controllers. This has worked previously, but now that I'm using a custom Jackson2 ObjectMapper these dates are instead being returned as arrays: [2020, 10, 12, 10, 57, 15, 200000000].

Why is this happening and how can I customize the ObjectMapper while still returning ISO-8601 dates?


Solution

  • JacksonAutoConfiguration creates an ObjectMapper with the WRITE_DATES_AS_TIMESTAMPS feature turned off, which returns LocalDateTimes as ISO-8601 strings. When you provide a custom ObjectMapper this default auto-configuration is turned off.

    This can be solved by, instead of providing a custom ObjectMapper, providing a Jackson2ObjectMapperBuilderCustomizer. This bean will be used by JacksonAutoConfiguration to customize the ObjectMapper while maintaining the auto-configured behaviour such as turning off the WRITE_DATES_AS_TIMESTAMPS feature.

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