ISO8601 with milliseconds in json using Jackson

冷暖自知 提交于 2019-11-28 03:56:42

问题


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

objectMapper.setDateFormat(new ISO8601DateFormat());

Nice but this ignores milliseconds, how can I get them in the dates without using the non-thread-safe SimpleDateFormatter?

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


回答1:


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

I've made a test with new Date() and the result was 2017-07-24T12:14:26.817Z (with the milliseconds).



来源:https://stackoverflow.com/questions/45276807/iso8601-with-milliseconds-in-json-using-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!