Java – iso8601 using Jackson in JSON in milliseconds

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

objectMapper.setDateFormat(new ISO8601DateFormat());

Good, but this ignores milliseconds. How can I get them in a date without using a non thread safe simpledateformatter?

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

Solution

ISO8601DateFormat. Format calls iso8601utils Format (date), which in turn calls format (date, false, timezone_z) – the false parameter tells Jackson not to include milliseconds

It seems that there is no way to configure this class or set any parameters, 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 tested with the new date (), and the result was 2017-07-24t12:14:26.817z (in milliseconds)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>