Search code examples
javadatejacksonjackson-databind

Deserialize a Date field of POJO using Jackson - Unable to deserliazing date field correctly


I am using Jackson to serialize and deserialize JSON. jackson-databind - 2.11.0

I have a POJO class as below:-

package PojoWithDateField;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;

public class Booking {

private String firstName;
private String lastName;

@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "DD-MM-YYYY",timezone = "Asia/Kolkata")
private Date checkin;
@JsonFormat(pattern = "DD-MM-YYYY")
private Date checkout;

public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public Date getCheckin() {
    return checkin;
}
public void setCheckin(Date checkin) {
    this.checkin = checkin;
}
public Date getCheckout() {
    return checkout;
}
public void setCheckout(Date checkout) {
    this.checkout = checkout;
}

}

I am serializing and deserializing as below:-

package PojoWithDateField;

import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CreatePojoWithDateField {

public static void main(String[] args) throws JsonProcessingException {
    Booking booking= new Booking();
    booking.setFirstName("Amod");
    booking.setLastName("Mahajan");
    booking.setCheckin(new Date());
    booking.setCheckout(new Date());
    
    ObjectMapper objectMapper = new ObjectMapper();

    
    String s = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(booking);
    
    System.out.println("Serialized JSON\n"+ s);
    
    
    Booking b1 = objectMapper.readValue(s, Booking.class);
    System.out.println(b1.getCheckin());
    
    SimpleDateFormat df = new SimpleDateFormat("DD-MM-YYYY");
    System.out.println(df.format(b1.getCheckin()));
}

}

Output:-

Serialized JSON
{
  "firstName" : "Amod",
  "lastName" : "Mahajan",
  "checkin" : "13-01-2021",
  "checkout" : "13-01-2021"
}
Sun Dec 27 00:00:00 IST 2020
362-12-2021

My expectation is whatever date I am passing same I want to retrieve.


Solution

  • Your date pattern is wrong. It should be dd-MM-yyyy, not DD-MM-YYYY. You are currently interpreting the days as "day in year" and the year as "week year".

    You can read more here: https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/text/SimpleDateFormat.html