Deserialize Java 8 LocalDateTime with JacksonMapper
Last Updated :
07 Jun, 2024
In Java applications, handling date and time efficiently is crucial. Java 8 introduced a new date and time API which includes the LocalDateTime
class. When working with RESTful APIs, serializing and deserializing LocalDateTime
objects is a common requirement. Jackson is a popular JSON processing library that provides support for Java 8 date and time types. In this article, we will demonstrate how to configure Jackson to deserialize LocalDateTime
in a Spring Boot application.
The main concept involves setting up the Spring Boot project, configuring Jackson to handle LocalDateTime
, and creating a REST Controller to demonstrate deserialization. To deserialize LocalDateTime
, Jackson requires the JavaTimeModule
to be registered with the application. This module provides serializers and deserializers for Java 8 date and time types.
Key Terminologies:
- Jackson: A popular JSON processing library for Java used for serializing and deserializing JSON data.
- LocalDateTime: A class in Java 8's
java.time
package representing date-time without a time zone in the ISO-8601 calendar system. - Deserialization: The process of converting JSON data into Java objects.
- JavaTimeModule: A Jackson module that provides serializers and deserializers for Java 8 date and time types.
- ObjectMapper: The main class in Jackson for converting JSON to Java objects and vice versa.
Implementation to Deserialize Java 8 LocalDateTime with JacksonMapper
Below are the implementation steps to Deserialize Java 8 LocalDateTime with JacksonMapper.
Step 1: Create Spring Boot project
We create a new Spring Boot project using Spring Initializr and add the following dependencies:
Dependencies:
- Spring Web
- Lombok
- Spring DevTools
Jackson Dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.17.1</version>
</dependency>
Project Structure:
After successfully project creation done, then the file structure will be like below:

Step 2: Configure application properties
Open the application.properties
file and add the following configuration:
spring.application.name=jackson-demo
server.port=8080
Step 3: Create the Event class
We will now create the Event class to define the Event model with the LocalDateTime field.
Go to src > main > java > org.example.jacksondemo > model > Event and put the below code.
Java
package org.example.jacksondemo.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;
public class Event {
private String name;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime eventDate;
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDateTime getEventDate() {
return eventDate;
}
public void setEventDate(LocalDateTime eventDate) {
this.eventDate = eventDate;
}
}
Step 4: Configure the Jackson
We will create the JacksonConfig class to register the JavaTimeModule with Jackson.
Go to src > main > java > org.example.jacksondemo > config > JacksonConfig and put the below code.
Java
package org.example.jacksondemo.config;
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());
return mapper;
}
}
Step 5: Create the EventController class
We will create the EventController class to handle the requests for creating and retrieving events.
Go to src > main > java > org.example.jacksondemo > controller > EventController and put the below code.
Java
package org.example.jacksondemo.controller;
import org.example.jacksondemo.model.Event;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/events")
public class EventController {
private List<Event> events = new ArrayList<>();
@PostMapping
public Event createEvent(@RequestBody Event event) {
events.add(event);
return event;
}
@GetMapping
public List<Event> getAllEvents() {
return events;
}
@GetMapping("/{name}")
public Event getEventByName(@PathVariable String name) {
return events.stream()
.filter(event -> event.getName().equalsIgnoreCase(name))
.findFirst()
.orElse(null);
}
@PutMapping("/{name}")
public Event updateEvent(@PathVariable String name, @RequestBody Event updatedEvent) {
Optional<Event> existingEventOpt = events.stream()
.filter(event -> event.getName().equalsIgnoreCase(name))
.findFirst();
if (existingEventOpt.isPresent()) {
Event existingEvent = existingEventOpt.get();
existingEvent.setName(updatedEvent.getName());
existingEvent.setEventDate(updatedEvent.getEventDate());
return existingEvent;
} else {
return null;
}
}
}
Step 6: Main Class
No changes are required in main class.
Java
package org.example.jacksondemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JacksonDemoApplication {
public static void main(String[] args) {
SpringApplication.run(JacksonDemoApplication.class, args);
}
}
pom.xml:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>jackson-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jackson-demo</name>
<description>jackson-demo</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 7: Run the application
After all the above steps done, now we will run the application and it will start at port 8080.
.jpg)
Step 8: Testing the Endpoints
1. Create the Event Endpoint:
POST http://localhost:8080/events
Output:

2. Get All the Events
GET http://localhost:8080/events
Output:

3. Get the Event by Event Name:
GET http://localhost:8080/events/Test%20Event
Output:

4. Update the Event:
PUT http://localhost:8080/events/Test%20Event
Output:

By the following these steps, we can seamlessly handle the LocalDateTime in the Spring Boot application. It ensures the efficient and accurate the date-time processing of the application.
Similar Reads
java.time.LocalDateTime Class in Java java.time.LocalDateTime class, introduced in Java 8, represents a local date-time object without timezone information. The LocalDateTime class in Java is an immutable date-time object that represents a date in the yyyy-MM-dd-HH-mm-ss.zzz format. It implements the ChronoLocalDateTime interface and in
4 min read
java.time.LocalDate Class in Java Java is the most popular programming language and widely used programming language. Java is used in all kind of application like as mobile application, desktop application, web application. In this Java java.time.LocalDate class is imported which represents to display the current date. java.time: It
4 min read
java.time.LocalTime Class in Java Java is the most popular programming language and widely used programming language. Java is used in all kinds of applications like mobile applications, desktop applications, web applications. As in Java, java.time.LocalTime class represents time, which is viewed as hour-minute-second. This class is
5 min read
java.time.OffsetDateTime Class in Java Java is the most popular programming language and widely used programming language. Java is used in all kind of application like mobile application, desktop application, web application. In this Java java.time.OffsetDate, Time class is imported which is an immutable representation of a date-time wit
4 min read
java.time.ZonedDateTime Class in Java ZonedDateTime is an immutable object representing a date-time along with the time zone. This class stores all date and time fields.This class stores time to a precision of nanoseconds and a time-zone, with a zone Offset used to handle local date-times. For example, the value â2nd October 2011 at 14:
8 min read
How to Convert Local Time to GMT in Java? Time conversion from IST or any standard time to GMT is necessary for locals to understand and reciprocate their international clients if they are connected overseas in terms of work or any purpose. Today we will have a look at a code where we convert the standard time of any country to GMT. Here we
4 min read