ISO8601 以 json 毫秒为单位使用 Jackson

ISO8601 with milliseconds in json using Jackson

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

ISO8601DateFormat.format 调用 ISO8601Utils.format(date),后者又调用 format(date, false, TIMEZONE_Z) - false 参数告诉杰克逊不要包括毫秒数。

这个好像没有办法配置class也没有设置任何参数,幸好可以扩展:

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;
    }
}

然后我们可以在对象映射器中使用这个新的class:

ObjectMapper objectMapper = new ObjectMapper();
ISO8601DateFormat dateFormat = new ISO8601WithMillisFormat();
objectMapper.setDateFormat(dateFormat);

我用 new Date() 进行了测试,结果是 2017-07-24T12:14:26.817Z(以毫秒为单位)。