我已经尽我所能解决了这个问题,但是我陷入了困境。由于某种原因,我在JSON字符串上添加了以下日期,而Mapper
在该日期上添加了小时。为什么要添加18:00:00?
String json = "{\n" +
" \"feature\": {\n" +
" \"due_date\": \"2019-02-25\"\n" +
" }\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
Wrapper feature = mapper.readValue(json, Wrapper.class);
Feature sample = feature.getFeature();
System.out.println(sample.getDueDate());
public class Feature implements Serializable {
@JsonDeserialize(using = DateAdaptor.class)
private String dueDate;
public Date getDueDate() {
return due_date;
}
@JsonProperty("due_date")
public void setDueDate(Date dueDate) {
this.due_date = dueDate;
}
}
public class Wrapper implements Serializable {
private Feature feature;
public Feature getFeature() {
return feature;
}
public void setFeature(Feature feature) {
this.feature = feature;
}
}
public class DateAdaptor extends StdDeserializer<Date>{
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
public DateAdaptor() {
this(null);
}
protected DateAdaptor(Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context)
throws IOException, JsonProcessingException {
String date = jsonparser.getText();
try {
return formatter.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
OUTPUT Sun Feb 24 18:00:00 CST 2019
答案 0 :(得分:0)
感谢您的帮助。我发现了我的问题所在。我在代码的错误部分/顺序上实现了该类。仅在“反序列化”对象时有效。因此,代码应如下所示。
public class Feature implements Serializable {
private String dueDate;
@JsonDeserialize(using = DateAdaptor.class)
public Date getDueDate() {
return due_date;
}
@JsonProperty("due_date")
public void setDueDate(Date dueDate) {
this.due_date = dueDate;
}