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

How to Properly Format LocalDateTime JSON in Spring Boot?

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 03:43:10916browse

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"
    }
  }

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>

    This dependency provides a converter that Spring will automatically register.

  2. 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"
  3. 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!

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