Formatting JSON LocalDateTime in Spring Boot
In Spring Boot applications, formatting Java 8 LocalDateTime values as JSON can present challenges. While converting regular dates is straightforward, LocalDateTime values often result in an undesirable format:
"startDate" : { "year" : 2010, "month" : "JANUARY", "dayOfMonth" : 1, "dayOfWeek" : "FRIDAY", "dayOfYear" : 1, "monthValue" : 1, "hour" : 2, "minute" : 2, "second" : 0, "nano" : 0, "chronology" : { "id" : "ISO", "calendarType" : "iso8601" } }
To address this issue, follow these steps:
Add the JSR-310 Converter Dependency:
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
This dependency provides a converter that Spring will automatically register.
Configure Application Properties:
spring.jackson.serialization.write_dates_as_timestamps=false
This setting ensures the usage of a proper converter, resulting in the following format:
"startDate": "2016-03-16T13:56:39.492"
Customize Date Format (Optional):
Use the @JsonFormat annotation to override the default format:
@JsonFormat(pattern="yyyy-MM-dd") public LocalDateTime getStartDate() { return startDate; }
The above is the detailed content of How to Properly Format LocalDateTime JSON in Spring Boot?. For more information, please follow other related articles on the PHP Chinese website!