Home >Java >javaTutorial >How to Customize JSON Serialization of Java 8 LocalDates in Spring Boot?
Customizing JSON Serialization of Java 8 LocalDates in Spring Boot
Problem:
When formatting a Java 8 LocalDateTime within a Spring Boot application, the resulting JSON representation consists of verbose field values instead of the desired ISO date format.
Solution:
Prior to Spring Boot 2.x, additional configuration is required to achieve the desired formatting:
Add the following dependency:
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")
Enable timestamp-free date serialization by adding the following to application.properties:
spring.jackson.serialization.write_dates_as_timestamps=false
Include the following annotation on the LocalDateTime property getter:
@JsonFormat(pattern="yyyy-MM-dd") public LocalDateTime getStartDate() { return startDate; }
Explanation:
Including the jackson-datatype-jsr310 dependency registers a converter for LocalDateTime. Configuring write_dates_as_timestamps to false ensures that the default converter is used, resulting in a serialized date in the ISO format yyyy-MM-dd. The @JsonFormat annotation further customizes the format to the desired string representation.
The above is the detailed content of How to Customize JSON Serialization of Java 8 LocalDates in Spring Boot?. For more information, please follow other related articles on the PHP Chinese website!