Spring Boot中OffsetDateTime的Jackson日期格式 [英] Jackson date-format for OffsetDateTime in Spring Boot

查看:512
本文介绍了Spring Boot中OffsetDateTime的Jackson日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆