ISO8601在json中使用Jackson的毫秒数
问题描述:
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
objectMapper.setDateFormat(new ISO8601DateFormat());
不错,但是这忽略了毫秒,我怎么能在没有使用非线程安全的SimpleDateFormatter
的日期得到它们?ISO8601在json中使用Jackson的毫秒数
答
ISO8601DateFormat.format
电话ISO8601Utils.format(date)
,进而调用format(date, false, TIMEZONE_Z)
- 在false
参数告诉杰克逊不包括毫秒。
似乎有没有办法来配置这个类也没有设置任何参数,但好在它可以扩展:
ObjectMapper objectMapper = new ObjectMapper();
ISO8601DateFormat dateFormat = new ISO8601WithMillisFormat();
objectMapper.setDateFormat(dateFormat);
:
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;
}
}
然后我们就可以在对象映射器使用这个新类
我用new Date()
进行了测试,结果为2017-07-24T12:14:26.817Z
(以毫秒为单位)。