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

what is circuit breaker in microservice

   A circuit breaker is a design pattern used in microservice architecture to improve the resilience and fault tolerance of the system. In a microservice architecture, multiple services work together to deliver a business function. When a service is not available, the downstream services depending on it may start to fail as well, leading to a cascading failure. A circuit breaker helps prevent cascading failures by monitoring the status of the dependent services. If a dependent service is not responding, the circuit breaker trips and redirects the traffic to a fallback mechanism, such as a cache or a default response. The circuit breaker periodically attempts to reconnect to the dependent service, and once it's available, it resumes directing traffic to it. The circuit breaker pattern helps prevent failures from spreading across the system, improves the availability of the overall system, and can help reduce the load on dependent services.

Java RoadMap