Home > Java > javaTutorial > How to Customize JSON Serialization of Java 8 LocalDates in Spring Boot?

How to Customize JSON Serialization of Java 8 LocalDates in Spring Boot?

Mary-Kate Olsen
Release: 2024-12-13 16:51:15
Original
175 people have browsed it

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:

  1. Add the following dependency:

    compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")
    Copy after login
  2. Enable timestamp-free date serialization by adding the following to application.properties:

    spring.jackson.serialization.write_dates_as_timestamps=false
    Copy after login
  3. Include the following annotation on the LocalDateTime property getter:

    @JsonFormat(pattern="yyyy-MM-dd")
    public LocalDateTime getStartDate() {
     return startDate;
    }
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template