BB8
BB8

Reputation: 41

Jackson JSON Date Deserialization to Timestamp

I am trying to map a JSON to POJO using Jackson2 for my REST method. The DueDate attribute in my POJO is of type java.util.date. I read that Jackson will deserialize JSON to timestamp by default. I want this behavior only. However, Jackson is converting the dueDate attribute to Date in my case.

Could anyone help me how to make Jackson deserialize the dueDate as timestamp.

JSON here ...

{ "atr1": null, "atr2": null, "dueDate": "2018-07-11" }

POJO here ..

public class Sample {
    private String atr1;
    private String atr1;
    private Date dueDate;
}

REST Api ...

    public Response create(String json) {                                        
            ObjectMapper mapper = new ObjectMapper();
            Sample sample1 = mapper.readValue(json,Sample.class);
 }

Thanks

More details... the value type of DueDate when the method is called from the actual UI object is Timestamp

object enter image description here

However, when the JSON is passed to REST for the method call, the type changes to Date. enter image description here

I want it to be Timestamp type. Because of this the SQL query which uses the dueDate as parameter doesn't fetch value properly.

Upvotes: 1

Views: 4905

Answers (2)

Dhiral Kaniya
Dhiral Kaniya

Reputation: 2051

You can use java.sql.timestamp in your pojo instead of java.util.Date.

import java.sql.Timestamp;

public class sample {
    private String atr1;
    private String atr2;
    private Timestamp dueDate;
}

You can access date timestamp with the same as you are doing above. I have also make code snippet for confirmation as below.

 public static void main( String[] args ) throws JsonParseException, JsonMappingException, IOException
    {
        String json = "{ \"atr1\": null, \"atr2\": null, \"dueDate\": \"2018-07-11\" }";
        ObjectMapper mapper = new ObjectMapper();
        sample sample1 = mapper.readValue(json, sample.class);
        System.out.println(sample1.getDueDate());
    }

output of above:- 2018-07-11 05:30:00.0

Upvotes: 2

Danial Jalalnouri
Danial Jalalnouri

Reputation: 630

You can use @JsonFormat for change the json date pattern like this:

public class Sample {
    private String atr1;
    private String atr1;
    @JsonFormat(shape = JsonFormat.Shape.NUMBER)
    private Date dueDate;
}

For more information read this link:

https://www.baeldung.com/jackson-jsonformat

Upvotes: 1

Related Questions