我正在尝试使用自定义日期格式序列化和反序列化非常简单的对象:
public class DateTimeTest {
private static final String DATE_PATTERN = "yyyyMMdd";
public static DateTime date = DateTime.now();
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
ObjectWriter writer = mapper.writer();
String str = writer.writeValueAsString(new Domain());
System.out.println(str);
ObjectReader reader = mapper.reader(Domain.class);
Domain domain = reader.readValue(str);
System.out.println(domain.getDate());
}
private static class Domain {
@JsonFormat(pattern = DATE_PATTERN)
private DateTime date;
public Domain() {
this.date = DateTime.now();
}
public DateTime getDate() {
return date;
}
public void setDate(DateTime date) {
this.date = date;
}
}
}
在执行 main 方法时,我希望得到类似于:
"date":"20151117"
20151117
但不幸的是得到了以下信息:
{"date":"20151117"}
20151117-01-01T00:00:00.000+03:00 (year is incorrect)
似乎 Jackson 忽略了对象反序列化的 @JsonFormat 注释,并将字符串视为 ISO-8601 表示法中的日期。有人知道解决方法吗?
<jackson.version>2.5.4</jackson.version>
<jodatime.version>2.8.1</version>
更新:如果我将日期模式更改为“dd/MM/yyyy”,那么我什至开始收到错误“IllegalArgumentException:格式无效”。所以 Jackson 肯定会忽略反序列化的日期模式。
最佳答案
根据 Jackson Release Notes仅从 2.6.0 版本添加了对 Joda @JsonFormat(pattern=...) 反序列化的支持。
关于java - Jackson 使用自定义日期格式错误地反序列化 Joda 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756260/