使用杰克逊的json中的ISO8601毫秒 [英] ISO8601 with milliseconds in json using Jackson
问题描述
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
objectMapper.setDateFormat(new ISO8601DateFormat());
很好但这忽略了毫秒,如何在不使用非线程的情况下在日期中获取它们安全 SimpleDateFormatter
?
Nice but this ignores milliseconds, how can I get them in the dates without using the non-thread-safe SimpleDateFormatter
?
推荐答案
ISO8601DateFormat.format
调用 ISO8601Utils.format(日期)
,后者又调用 format(date,false, TIMEZONE_Z)
- false
参数告诉jackson不包括毫秒。
ISO8601DateFormat.format
calls ISO8601Utils.format(date)
, which in turn calls format(date, false, TIMEZONE_Z)
- the false
parameter tells jackson to don't include the milliseconds.
似乎没有办法配置这个类设置任何参数,但幸运的是它可以扩展:
There seems to be no way to configure this class nor set any parameter, but fortunately it can be extended:
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;
}
}
然后我们可以在对象映射器中使用这个新类:
Then we can use this new class in the object mapper:
ObjectMapper objectMapper = new ObjectMapper();
ISO8601DateFormat dateFormat = new ISO8601WithMillisFormat();
objectMapper.setDateFormat(dateFormat);
我用新日期()$ c进行了测试$ c>,结果是
2017-07-24T12:14:26.817Z
(以毫秒为单位)。
I've made a test with new Date()
and the result was 2017-07-24T12:14:26.817Z
(with the milliseconds).
这篇关于使用杰克逊的json中的ISO8601毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!