Spring Boot 中 OffsetDateTime 的 Jackson 日期格式 [英] Jackson date-format for OffsetDateTime in Spring Boot
问题描述
我正在尝试从 Spring 应用程序输出 OffsetDateTime,并在我的 application.properties 中具有以下属性:
I'm trying to output an OffsetDateTime from my Spring application, and have in my application.properties these properties:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
spring.jackson.date-format=yyyy-MM-dd'T'HH:mm
然而,当返回日期时,它的格式为
However when the date is returned it is formatted as
"2017-01-30T16:55:00Z"
我应该如何正确配置 Spring 应用程序中的日期格式?
How should I correctly configure the format for the date in my Spring application?
推荐答案
所以我已经设法找到了一个解决方案,但如果您有替代方案,请发布.
So I've managed to figure out a solution, but if you have an alternative please post it.
我最终创建了一个新的主 ObjectMapper
bean,并为 OffsetDateTime
注册了一个带有自定义序列化程序的新模块.我可以在这里设置我自己的日期格式,使用 java.time.format.DateTimeFormatter
.我还必须用我的映射器注册 JavaTimeModule
.
I ended up creating a new primary ObjectMapper
bean, and registering a new module with a custom serializer for OffsetDateTime
. I'm able to set my own date format in here, using java.time.format.DateTimeFormatter
. I also had to register the JavaTimeModule
with my mapper.
@Configuration
public class JacksonOffsetDateTimeMapper{
@Primary
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(OffsetDateTime.class, new JsonSerializer<OffsetDateTime>() {
@Override
public void serialize(OffsetDateTime offsetDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(offsetDateTime));
}
});
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
这篇关于Spring Boot 中 OffsetDateTime 的 Jackson 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!