【问题标题】:ISO8601 with milliseconds in json using JacksonISO8601 使用 Jackson 在 json 中以毫秒为单位
【发布时间】:2017-12-29 19:35:24
【问题描述】:
【问题讨论】:
标签:
java
json
jackson
datetime-format
iso8601
【解决方案1】:
ISO8601DateFormat.format 调用ISO8601Utils.format(date),后者又调用format(date, false, TIMEZONE_Z) - false 参数告诉杰克逊不要包括毫秒。
貌似没有办法配置这个类,也没有设置任何参数,还好可以扩展:
public class ISO8601WithMillisFormat extends ISO8601DateFormat {
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true); // "true" to include milliseconds
toAppendTo.append(value);
return toAppendTo;
}
}
然后我们可以在对象映射器中使用这个新类:
ObjectMapper objectMapper = new ObjectMapper();
ISO8601DateFormat dateFormat = new ISO8601WithMillisFormat();
objectMapper.setDateFormat(dateFormat);
我用new Date() 进行了测试,结果是2017-07-24T12:14:26.817Z(以毫秒为单位)。