Home > Mobile >  Spring Web - How to format `Instant` in a specific way
Spring Web - How to format `Instant` in a specific way

Time:06-26

I am developing a REST controller in Spring. One of the requirements is to be able to handle dates only in ISO-8601 format.

I'm using Instant for this purpose. When used in request DTOs, it handles incoming dates perfectly. But when used in response DTOs, the output format needs a little change.

The date in json output looks like this:
2022-02-03T15:00:00Z

But it should look like this:
2022-02-03T15:00:00.000Z

I want to specify how RestController formats Instant. To that end, I can think of several solutions.

  1. Is there a way to override how RestController converts a specific class to string? Perhaps in the same way that exception handling is done (with @ExceptionHandler).
  2. Is there a way to intercept the DTO after it gets converted to json? Before getting sent off to the client, that is.
  3. Is there a way to simply annotate the return value of the rest controller's method to achieve the desired format?

CodePudding user response:

If you use Jackson to serialize and deserialize JSON data in you Spring Boot project, I would like to suggest you use LocalDate/LocalDateTime types for your needs. Then, you can edit your application.properties and add here such row:

jackson.date-format=com.fasterxml.jackson.databind.util.ISO8601DateFormat

Also, you need to have a Maven/Gradle dependency jackson-modules-java8

Probably, it will also work with Instant type, but I didn't test it.

Also, if you use your own ObjectMapper (not autoconfigured by Spring) you need to add Jackson Module to it. Here is an explanation in another question.

CodePudding user response:

The solution was to use JavaTimeModule. I defined the ObjectMapper bean configuration for Spring's DI, and then used the @JsonFormat annotation on the Instant field of the DTO.

One thing to note is that when using the pattern field of @JsonFormat, the timezone field becomes mandatory for some reason. Even setting the time-zone in application.properties doesn't work. I set timezone = "0", as I need to use UTC dates.

  • Related