gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:17:05 25 4
gpt4 key购买 nike

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

在 Java 方面,Jackson 使用的 getter 很简单:

public Instant getMyInstantVal() { return myInstantVal; }

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

到目前为止,我的解决方案(并且工作正常)是使用 @JsonGetter 创建一个替代 setter/getter ,这会导致 Jackson 使用此方法来序列化 myInstantVal :
@JsonGetter("myInstantVal")
public long getMyInstantValEpoch() {
return myInstantVal.toEpochMilli();
}

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

最佳答案

您只需要阅读链接到的自述文件。强调我的:

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.

关于angularjs - 让 Jackson 将 Java 8 Instant 序列化为纪元毫秒的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com