Spring Data JPA supports the mapping of Java 8 date and time types to database columns. However, the default JSON serialization format for ZonedDateTime can produce verbose output. This article explores how to format ZonedDateTime to ISO format during JSON serialization.
Despite using the @DateTimeFormat annotation with iso = DateTimeFormat.ISO.DATE_TIME, the JSON serialization of ZonedDateTime still produces a detailed object. The goal is to format ZonedDateTime to a more concise ISO format.
The JSON serialization problem is likely caused by Jackson, which handles JSON serialization in Spring Data JPA. To resolve this, Jackson's module for the Java 8 date and time API needs to be added.
Add the following dependency to your pom.xml:
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.6.0</version> </dependency>
After adding the dependency, register the JavaTimeModule with Jackson:
ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule());
The @JsonFormat annotation on the ZonedDateTime getter method can be used to customize the date format during serialization. For example:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") public ZonedDateTime getTime() { return time; }
This will format the ZonedDateTime to the ISO format: yyyy-MM-dd'T'HH:mm:ss.SSSZ.
The following example demonstrates the usage of the JavaTimeModule and format customization:
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 of this example would be:
{"time":"2015-07-25T23:09:01.795+0700"}
By adding Jackson's JavaTimeModule and using the @JsonFormat annotation, you can control the JSON serialization format of ZonedDateTime and prevent the transfer of unnecessary data, optimizing the performance and reducing the size of JSON payloads.
The above is the detailed content of How to Format ZonedDateTime to ISO 8601 in Spring Data JPA JSON Serialization?. For more information, please follow other related articles on the PHP Chinese website!