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

IPL 2025: The Ultimate Season Preview, Stats, and Predictions

 The Indian Premier League (IPL) 2025 is set to be bigger and better than ever. With a mega auction, new regulations, and rising superstars, this season is shaping up to be the most thrilling edition in IPL history. Let’s dive deep into team analyses, key player stats, historic milestones, and predictions to see what IPL 2025 has in store! IPL 2025 at a Glance Start Date: March 22, 2025 Final Match Venue: Eden Gardens, Kolkata Total Matches: 74 Teams: 10 New Rule: Introduction of 'Power Boost Over' (Allows a team to add an extra over to Powerplay if all wickets are intact by the 8th over) --- Interesting IPL 2025 Data & Records 1. The ₹100 Crore Auction - Highest Spending in IPL History Total Money Spent: ₹1050 crore (~$125 million) Most Expensive Player: Rishabh Pant (Lucknow Super Giants) - ₹27 crore Shreyas Iyer (Punjab Kings) - ₹26.75 crore Trent Boult (Delhi Capitals) - ₹18.5 crore 2. The ‘Orange Cap’ Race - Run-Scoring Machines Predicting the top contenders for the hi...

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...

How I Cracked 3 Job Offers as a Java Developer – My Journey & Key Strategies

 Job hunting can be overwhelming, especially when you’re aiming for a great opportunity that matches your experience and skills. As a Java developer with nearly six years of experience, I recently went through multiple interview processes and ended up receiving six job offers. It wasn’t luck—it was a mix of strategy, preparation, and the right mindset. In this blog, I’ll share my approach, preparation techniques, and lessons learned to help you navigate your job search and ace your interviews. 1. The Turning Point: Why I Started Looking for a Change Like many professionals, I reached a phase where I wanted career growth, better compensation, and challenging projects. While my experience was strong, I realized that just having skills wasn’t enough—I needed to present them effectively in interviews. 2. Building the Right Mindset for Job Hunting Before diving into job applications, I focused on three key aspects: Confidence: Believing in my experience and technical expertise. Clarity:...