英文:
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
};
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论