angularjs – 让Jackson将Java 8 Instant序列化为纪元毫秒的有效方法吗?

前端之家收集整理的这篇文章主要介绍了angularjs – 让Jackson将Java 8 Instant序列化为纪元毫秒的有效方法吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用带有Jackson JSON解析后端的Spring RestControllers,前端使用AngularJS.我正在寻找一种有效的方法让Jackson序列化一个Instant作为纪元毫秒,以便随后使用JavaScript代码. (在浏览器方面,我希望通过Angular的Date Filter提供epoch ms:{{myInstantVal | date:’short’}}以获得我想要的日期格式.)

在Java方面,杰克逊将使用的吸气剂就是:

public Instant getMyInstantVal() { return myInstantVal; }

序列化不会按原样运行,因为默认情况下,jackson-datatype-jsr310不会返回Epoch毫秒数.我看着将@JsonFormat添加到上面的getter中以将Instant变成前端可以使用的东西,但是它遇到两个问题:(1)我可以提供它的模式显然仅限于SimpleDateFormat,它不提供“ epoch milliseconds“选项,以及(2)当我尝试将Instant作为格式化日期发送到浏览器时,Jackson会抛出异常,因为@JsonFormat注释需要Instants的TimeZone属性,我不想硬编码为它会因用户而异.

到目前为止我的解决方案(并且工作正常)是使用@JsonGetter创建替换getter,这会导致Jackson使用此方法来序列化myInstantVal:

@JsonGetter("myInstantVal")
public long getMyInstantValEpoch() {
    return myInstantVal.toEpochMilli();
}

这是正确的方法吗?或者是否有一个很好的注释,我错过了我可以放在getMyInstantVal()所以我不必创建这些额外的方法

最佳答案
您只需阅读链接到的README.我的重点:

Most JSR-310 types are serialized as numbers (integers or decimals as appropriate) if the SerializationFeature#WRITE_DATES_AS_TIMESTAMPS feature is enabled,and otherwise are serialized in standard ISO-8601 string representation.

[…]

Granularity of timestamps is controlled through the companion features SerializationFeature#WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS and DeserializationFeature#READ_DATE_TIMESTAMPS_AS_NANOSECONDS. For serialization,timestamps are written as fractional numbers (decimals),where the number is seconds and the decimal is fractional seconds,if WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS is enabled (it is by default),with resolution as fine as nanoseconds depending on the underlying JDK implementation. If WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS is disabled,timestamps are written as a whole number of milliseconds.

猜你在找的Spring相关文章