加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 使用Jackson在json中使用毫秒的ISO8601

发布时间:2020-12-14 06:02:00 所属栏目:Java 来源:网络整理
导读:import com.fasterxml.jackson.databind.util.ISO8601DateFormat;objectMapper.setDateFormat(new ISO8601DateFormat()); 很好但这忽略了毫秒,如何在不使用非线程安全的SimpleDateFormatter的情况下在日期中获取它们? https://github.com/FasterXML/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参数告诉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);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读