In Spring Boot, formatting Java 8 LocalDateTime objects for JSON output can pose challenges. While traditional date formatting works as expected, LocalDateTime presents a unique formatting issue.
One common problem is that LocalDateTime fields are converted to a detailed structure with attributes like "year," "month," and so on, instead of a simple string representation. To address this issue, additional configuration is required.
To resolve this, follow these steps:
Add the Jackson Dependency:
Include the following dependency in your project:
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")
Configure Spring:
Add the following line to your application.properties file:
spring.jackson.serialization.write_dates_as_timestamps=false
Now, Spring Boot will automatically register a LocalDateTime converter. However, if you want to customize the date format, you can use the following annotations:
Note: In Spring Boot 2.x, the configuration steps described above are no longer required, as Spring now natively handles LocalDateTime conversion.
The above is the detailed content of How to Properly Serialize Java 8 LocalDateTime to JSON in Spring Boot?. For more information, please follow other related articles on the PHP Chinese website!