Home  >  Article  >  Java  >  How to Properly Serialize Java 8 LocalDateTime to JSON in Spring Boot?

How to Properly Serialize Java 8 LocalDateTime to JSON in Spring Boot?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-23 22:27:11156browse

How to Properly Serialize Java 8 LocalDateTime to JSON in Spring Boot?

Converting Java 8 LocalDateTime to JSON in Spring Boot

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:

  1. Add the Jackson Dependency:

    • Include the following dependency in your project:

      compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")
  2. Configure Spring:

    • Add the following line to your application.properties file:

      spring.jackson.serialization.write_dates_as_timestamps=false
    • This will ensure that a proper converter is used to serialize dates as strings.

Now, Spring Boot will automatically register a LocalDateTime converter. However, if you want to customize the date format, you can use the following annotations:

  • @JsonFormat: Use this annotation to specify the desired date format.
  • @DateTimeFormat: Use this annotation to specify the ISO date format.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn