小编典典

使用Jackson的json中的ISO8601毫秒

json

import com.fasterxml.jackson.databind.util.ISO8601DateFormat;

objectMapper.setDateFormat(new ISO8601DateFormat());

很好,但这忽略了毫秒,如何在不使用非线程安全的情况下获取日期SimpleDateFormatter呢?

https://github.com/FasterXML/jackson-
databind/blob/master/src/main/java/com/fasterxml/jackson/databind/util/ISO8601DateFormat.java


阅读 662

收藏
2020-07-27

共1个答案

小编典典

ISO8601DateFormat.formatCalls
ISO8601Utils.format(date),反过来又调用format(date, false, TIMEZONE_Z)-
false参数告诉Jackson不包括毫秒。

似乎没有办法配置此类或设置任何参数,但是幸运的是可以对其进行扩展:

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(毫秒)。

2020-07-27