简体   繁体   中英

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 在此处输入图片说明

However, when the JSON is passed to REST for the method call, the type changes to Date . 在此处输入图片说明

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM