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

Preparing for a Java Fresher Interview: Key Concepts and Tips

 When preparing a fresher graduate for a position involving Java technology, it’s important to gauge their understanding of fundamental concepts, problem-solving skills, and their ability to learn and adapt. Here are some questions and points that are important for freshers: Key Areas to Focus On: 1. Core Java Concepts:    - Object-Oriented Programming (OOP) principles: encapsulation, inheritance, polymorphism, and abstraction.    - Basic syntax and structure of a Java program.    - Data types, variables, operators, and control structures (loops, conditionals). 2. Advanced Java Concepts:    - Exception handling.    - Collections framework (List, Set, Map).    - Multithreading and concurrency basics.    - Input/Output (I/O) and serialization. 3. Java Development Tools and Environment:    - Knowledge of Integrated Development Environments (IDEs) like Eclipse or IntelliJ IDEA.    - Basic understanding of build tools like Maven or Gradle.    - Familiarity with version control systems like

java Interview Goal

                                                  Hi All,         I write this blog for Fresher  And  Experience  who have start Career In IT_Industry With  java Technology, I am not a professional blogger, I am  working  as Java Developer since last 2 years,   The main reason to write this blog is to share my Experience In Interviews. ABOUT THE AUTHOR           Nice to meet you, I’m Akshay Ingole. I’m a not a professional blogger ,  I am  working  as Java Developer since last 2 years,   The main reason to write this blog is to share my Experience In Interviews as well as share the topics that trending in java.   I hope It is Useful For All.