[英]Deserialize a Date field of POJO using Jackson - Unable to deserliazing date field correctly
我正在使用 Jackson 序列化和反序列化 JSON.jackson-databind - 2.11.0
我有一个 POJO class 如下:-
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;
}
}
我正在序列化和反序列化如下:-
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
我的期望是我想要检索的任何日期。
你的日期模式是错误的。 它应该是dd-MM-yyyy
,而不是DD-MM-YYYY
。 您目前将天数解释为“一年中的某一天”,将年份解释为“一年中的一周”。
您可以在这里阅读更多内容: https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/text/SimpleDateFormat.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.