Spring Data JPA – ZonedDateTime format for json serialization

I guess that you are using Jackson for json serialization, Jackson now has a module for Java 8 new date time API, https://github.com/FasterXML/jackson-datatype-jsr310.

Add this dependency into your pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.6.0</version>
</dependency>

And this is its usage:

 public static void main(String[] args) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    System.out.println(objectMapper.writeValueAsString(new Entity()));
}

static class Entity {
    ZonedDateTime time = ZonedDateTime.now();

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
    public ZonedDateTime getTime() {
        return time;
    }
}

The output is:

{"time":"2015-07-25T23:09:01.795+0700"}

Note : If your Jackson version is 2.4.x use

objectMapper.registerModule(new JSR310Module());

Hope this helps!

Leave a Comment