Home > Java > javaTutorial > How to Properly Format LocalDateTime JSON in Spring Boot?

How to Properly Format LocalDateTime JSON in Spring Boot?

Barbara Streisand
Release: 2024-11-21 03:43:10
Original
913 people have browsed it

How to Properly Format LocalDateTime JSON in Spring Boot?

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"
    }
  }
Copy after login

To address this issue, follow these steps:

  1. Add the JSR-310 Converter Dependency:

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>
    Copy after login

    This dependency provides a converter that Spring will automatically register.

  2. Configure Application Properties:

    spring.jackson.serialization.write_dates_as_timestamps=false
    Copy after login

    This setting ensures the usage of a proper converter, resulting in the following format:

    "startDate": "2016-03-16T13:56:39.492"
    Copy after login
  3. Customize Date Format (Optional):

    Use the @JsonFormat annotation to override the default format:

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

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!

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