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

huangapple go评论92阅读模式
英文:

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

问题

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

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

英文:

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?

答案1

得分: 0

JacksonAutoConfiguration创建一个带有WRITE_DATES_AS_TIMESTAMPS功能关闭的ObjectMapper,该功能会将LocalDateTimes返回为ISO-8601字符串。当您提供自定义的ObjectMapper时,会关闭此默认自动配置。

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

@Configuration
public class Config {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer objectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> {
            // 在保持自动配置的同时自定义ObjectMapper
        };
    }
}
英文:

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
        };
    }
}

huangapple
  • 本文由 发表于 2020年10月19日 18:51:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64425836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定