Java 8 brought many new features and improvements, including the new LocalDateTime API for handling date and time values. This API provides a rich set of classes and methods for representing, parsing, and formatting date and time values. In this blog post, we’ll see how to use the Java 8 LocalDateTime API in combination with Spring Boot to format JSON responses.



Setting up the Project

To get started, you’ll need to set up a new Spring Boot project. You can do this either through the Spring Initializer web site or through your favorite IDE. Once you have created the project, add the following dependencies to your build file:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
  <version>2.11.0</version>
</dependency>

These dependencies will allow you to use the Java 8 LocalDateTime API with Jackson, the default JSON serialization library used by Spring Boot.



Configuring the JSON Serialization

Next, you’ll need to configure the JSON serialization to use the Java 8 LocalDateTime API. You can do this by adding the following configuration to your application.properties file:

spring.jackson.serialization.write-dates-as-timestamps=false

This configuration tells Jackson to use the ISO 8601 format for serializing dates, which is the default format for the Java 8 LocalDateTime API.



Creating a Model Class

To demonstrate how to use the Java 8 LocalDateTime API with JSON, we’ll create a simple model class that represents an event:

import java.time.LocalDateTime;

public class Event {

  private String name;
  private LocalDateTime startDate;

  public Event(String name, LocalDateTime startDate) {
    this.name = name;
    this.startDate = startDate;
  }

  public String getName() {
    return name;
  }

  public LocalDateTime getStartDate() {
    return startDate;
  }
}


Creating a REST Endpoint

Next, we’ll create a simple REST endpoint that returns a list of events in JSON format:

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EventController {

  @GetMapping("/events")
  public List<Event> getEvents() {
    return Arrays.asList(
      new Event("Event 1", LocalDateTime.of(2022, 1, 1, 0, 0)),
      new Event("Event 2", LocalDateTime.of(2022, 2, 1, 0, 0)),
      new Event("Event 3", LocalDateTime.of(2022, 3, 1, 0, 0))
    );
  }
}


Testing the REST Endpoint

You can now start the Spring Boot application and test the REST endpoint by sending a GET request to http://localhost:8080/events. The response should be a JSON representation of the events list, with the start date formatted using the ISO 8601 format:

[  {    "name": "Event 1",    "startDate": "2022-01-01T00:00:00"  },  {    "name": "Event 2",    "startDate": "2022-02-01T00:00:00"  },  {    "name": "Event 3",    "startDate": "2022-03-01T00:00:00"  }]


Customizing the Date Format

If you need to use a different date format, you can configure the Jackson ObjectMapper bean in your application configuration:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {

  @Bean
  public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(com.fasterxml.jackson.databind.SerializationFeature.
      WRITE_DATES_AS_TIMESTAMPS , false);
    return mapper;
  }
}

With this configuration, you can use the @JsonFormat annotation to specify the date format for each property:

import java.time.LocalDateTime;

import com.fasterxml.jackson.annotation.JsonFormat;

public class Event {

  private String name;

  @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
  private LocalDateTime startDate;

  public Event(String name, LocalDateTime startDate) {
    this.name = name;
    this.startDate = startDate;
  }

  public String getName() {
    return name;
  }

  public LocalDateTime getStartDate() {
    return startDate;
  }
}

With this configuration, the date will be serialized in the specified format:

[  {    "name": "Event 1",    "startDate": "2022-01-01 00:00:00"  },  {    "name": "Event 2",    "startDate": "2022-02-01 00:00:00"  },  {    "name": "Event 3",    "startDate": "2022-03-01 00:00:00"  }]


Conclusion

In this blog post, we saw how to use the Java 8 LocalDateTime API with Spring Boot to format JSON responses. We covered the basic configuration required to get started, as well as how to customize the date format. With these tips, you should be able to use the Java 8 LocalDateTime API with confidence in your next Spring Boot project.



Leave a Reply