Spring Boot, define timezone for Json and java.time.* globally

Viewed 7358

I'm using Spring Boot 1.5.3, Spring Data REST, HATEOAS to create a REST service. I use java.time.* date/times in my application and I'm storing that in UTC format in the database. I want to follow best practice and return UTC dates in my REST endpoints.

Using @JsonFormat I'm able to accomplish to that:

@JsonFormat(timezone = "UTC", pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
@LastModifiedDate
private LocalDateTime lastModifiedDate;

I would like to avoid to annotate all my beans with that, and I would prefer to have a global configuration. According to this enhancemente request, I was able to solve 50% of my problem with this configuration:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {

        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
            jacksonObjectMapperBuilder.serializers(
                    new LocalDateTimeSerializer(new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss").toFormatter()));
            jacksonObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(
                    new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").toFormatter()));
        }

    };
}

This fix the pattern problem but not the timezone problem. My timezone continue to remain the local timezone. Is there a graceful way to set the timezone of JSON serializer to UTC like the property spring.jackson.time-zone=UTC that unfortunately work just for java.util.time?

1 Answers
Related