Skip to main content

How to parse JSON with date field in Java - Jackson @JsonDeserialize Annotation Example

How to Parse JSON with Date Field in Java - Jackson `@JsonDeserialize` Annotation Example

Parsing JSON in Java is a common task, but dealing with date fields requires a little extra attention. JSON treats everything as a string, but Java has strong typing, meaning dates need to be handled differently.

In this post, we will see how to parse a JSON with a date field using Jackson, focusing on the `@JsonDeserialize` annotation.

Example Scenario

Let’s assume we have a simple JSON that includes a date field:

```

{

  "name": "John Doe",

  "birthDate": "2024-09-05"

}

```


In Java, we might want to map this to a class with a `LocalDate` for `birthDate`. This is where Jackson's `@JsonDeserialize` annotation comes into play.

Step-by-Step Example

Step 1: Add Jackson Dependency

First, make sure you have the Jackson dependency in your `pom.xml` if you’re using Maven:

```

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.13.0</version>

</dependency>

```

Step 2: Create the POJO

Let’s create a class `Person` that maps to the JSON structure:

```

import com.fasterxml.jackson.annotation.JsonFormat;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.time.LocalDate;

public class Person {

    private String name;

    @JsonDeserialize(using = LocalDateDeserializer.class)

    @JsonFormat(pattern = "yyyy-MM-dd")  // This defines the format in which date is expected

    private LocalDate birthDate;

    // Getters and Setters

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public LocalDate getBirthDate() {

        return birthDate;

    }

    public void setBirthDate(LocalDate birthDate) {

        this.birthDate = birthDate;

    }

}

```

Step 3: Create a Custom Deserializer

We need to create a custom deserializer for `LocalDate`. Jackson will use this to convert the date string into a `LocalDate` object.

```
import com.fasterxml.jackson.core.JsonParser;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.DeserializationContext;

import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

    @Override

    public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)

            throws IOException, JsonProcessingException {

        String date = jsonParser.getText();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        return LocalDate.parse(date, formatter);

    }

}

```

Step 4: Parse the JSON


Finally, you can use Jackson to parse the JSON into your `Person` object:

```
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParserExample {

    public static void main(String[] args) {

        String json = "{ \"name\": \"John Doe\", \"birthDate\": \"2024-09-05\" }";

                ObjectMapper objectMapper = new ObjectMapper();

                try {

            Person person = objectMapper.readValue(json, Person.class);

            System.out.println("Name: " + person.getName());

            System.out.println("Birth Date: " + person.getBirthDate());

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

```
Output:

```

Name: John Doe

Birth Date: 2024-09-05

```

Summary


In this example, we used Jackson’s `@JsonDeserialize` to handle the date field. This technique is especially useful when dealing with date formats in JSON that need to be mapped to Java’s `LocalDate` or `Date` objects.

By using a custom deserializer and `@JsonFormat`, you can easily control how dates are handled and parsed in your Java application.


Comments

Popular posts from this blog

JDK 25: The new features in Java 25

 Java Development Kit (JDK) 25, scheduled for release in September 2025, is set to introduce several significant enhancements. Here's an overview of the notable features: 1. Stable Values API (Preview): This feature introduces stable values—objects holding immutable data treated as constants by the Java Virtual Machine (JVM). By allowing greater flexibility in initialization timing compared to final fields, stable values aim to improve application startup times. They enable performance optimizations akin to constant-folding, previously exclusive to JDK code, and ensure thread-safe, single-time initialization. This decouples the creation of stable values from their initialization without significant performance penalties.  2. Removal of 32-bit x86 Port: JDK 25 plans to eliminate both the source code and build support for the 32-bit x86 port, which was deprecated in JDK 24. Maintaining this port has become less beneficial, especially with the challenges in keeping it updated wit...

Java 24 Released: What's New and Why It Matters?

 Oracle has officially released Java 24 on March 18, 2025, bringing a host of new features aimed at improving developer productivity, security, and performance. This release includes over 20 enhancements, making Java even more powerful for modern application development. Let’s dive into the key features and improvements in Java 24 and understand why they matter. --- 1. AI and Machine Learning Support Java 24 introduces features designed to enhance AI-powered applications. Developers can now integrate AI models and perform AI inference more efficiently using built-in Java capabilities. Why It Matters? With AI becoming a crucial part of modern applications, Java 24 makes it easier to process and deploy AI models without relying heavily on third-party libraries. --- 2. Post-Quantum Cryptography To prepare for the future threats of quantum computing, Java 24 includes new cryptographic algorithms that protect against potential security breaches. Why It Matters? Quantum computers could p...

Hanumankind’s ‘Run It Up’: A New Wave in Indian Hip-Hop

 Indian rapper Hanumankind, born Sooraj Cherukat, has recently released a new single titled "Run It Up," produced by Kalmi. The official music video debuted last week and showcases Hanumankind's dynamic performance style.  Prior to this release, Hanumankind gained international recognition with his 2024 hit "Big Dawgs," also produced by Kalmi. The track's innovative music video, featuring Hanumankind performing within a "well of death" motordrome, contributed to its viral success.  "Run It Up" continues Hanumankind's exploration of blending traditional Indian musical elements with contemporary hip-hop beats. The track reflects his unique style, influenced by his upbringing in both Kerala, India, and Houston, Texas.  Fans and critics have praised "Run It Up" for its energetic rhythm and catchy hooks. Discussions on platforms like Reddit highlight the song's fusion of genres and its potential to further elevate Hanumankind...