我正在尝试从我的 Spring 应用程序中输出一个 OffsetDateTime,并在我的 application.properties 中有这些属性:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
spring.jackson.date-format=yyyy-MM-dd'T'HH:mm
但是,当返回日期时,它的格式为
"2017-01-30T16:55:00Z"
我应该如何正确配置 Spring 应用程序中的日期格式?
最佳答案
所以我已经设法找出一个解决方案,但如果你有替代方案,请发布它。
我最终创建了一个新的主 ObjectMapper
bean,并使用 OffsetDateTime
的自定义序列化程序注册了一个新模块。我可以在这里设置我自己的日期格式,使用 java.time.format.DateTimeFormatter
。我还必须用我的映射器注册 JavaTimeModule
。
@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;
}
}
关于java - Spring Boot 中 OffsetDateTime 的 jackson 日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41876037/