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.


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.

Deserialize Java 8 LocalDateTime with JacksonMapper

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.

Similar Reads

Implementation to Deserialize Java 8 LocalDateTime with JacksonMapper

Below are the implementation steps to Deserialize Java 8 LocalDateTime with JacksonMapper....