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

What is JDK, JRE and JVM?

What are JDK, JRE, and JVM: JDK :- Java Development Kit (in short JDK) is Kit which provides the environment to Develop and execute(run ) the Java program. For eg. You(as Java Developer) are developing an accounting application on your machine, so what do you going to need into your machine to develop and run this desktop app? You are going to need  J-D-K  for that purpose for this you just need to go to the official website of sun or oracle to download the latest version of JDK into your machine. Hence, JDK is a kit(or package) which includes two things i) Development Tools(to provide an environment to develop your java programs) and ii) JRE (to execute your java program). JDK is only used by Java Developers. JRE: - Java Runtime Environment (to say JRE) is an installation package which provides an environment to only run(not develop) the java program(or application)onto your machine. For eg(continuing with the same example) after developing your accounting ap...

The Future of Java Developers in the Age of AI and ChatGPT

  In today's rapidly evolving tech landscape, AI tools like ChatGPT are becoming more integrated into the software development process. As a Java developer, whether you're just starting out or have years of experience, you might wonder: How can I stay relevant and succeed in the age of AI? In this post, we'll explore practical strategies to ensure you not only survive but thrive as a Java developer in this AI-driven world. 1. Embrace AI as a Tool, Not a Threat AI isn't here to replace you—it's here to help you. Tools like ChatGPT can automate repetitive tasks, assist with coding challenges, and even generate code snippets, allowing you to focus on more complex and creative aspects of development. For Freshers: Use AI tools to learn and understand Java more quickly. Let them assist you in writing code, but make sure you're also learning the logic and concepts behind it. For Experienced Developers: Integrate AI tools into your workflow to enhance productivity. L...

What are the best opportunities for java in 2021?

Firstly, Java is widely used for building enterprise-scale web applications. Java is known to be extremely stable and so, many large enterprises have adopted it. If you are looking for a development based job at a large organization, Java is the language that you should learn. It is widely used in Android App Development. So if anyone is willing to find a career in Android App Development, he/she should have an intermediate level of experience in Java. Some of the different domains where Java is used widely are as follows: Financial services:  It is used in server-side applications. Big Data:  Hadoop MapReduce framework is written using Java. Banking:  To deal with transaction management. Stock market:  To write algorithms as to which company they should invest in. Retail:  Billing applications that you see in a store/restaurant are completely written in Java. Android:  Applications are either written in Java or use Java API. Scientific and Research Communi...