简体   繁体   English

Jackson Java 8 DateTime序列化

[英]Jackson Java 8 DateTime serialisation

Jackson operates java.time.Instant with WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS ( READ_ as well) enabled by default. Jackson运行java.time.Instant,默认启用WRITE_DATE_TIMESTAMPS_AS_NANOSECONDSREAD_ )。 jackson-datatype-jsr310 杰克逊-数据类型- jsr310

It produces JSON like this 它像这样生成JSON

{ "createDate":1421261297.356000000, "modifyDate":1421261297.356000000 }

In JavaScript it's much easier to get Date from traditional millis timestamp (not from seconds/nanos as above), like new Date(1421261297356) . 在JavaScript中,从传统的millis时间戳(而不是像上面的秒/ nanos)那样获得Date要容易得多,比如new Date(1421261297356)

I think there should be some reason to have the nanos approach by default, so what is that reason? 我认为应该有一些理由默认采用纳米方法,那么这是什么原因呢?

One way is to create your own Jackson module and do the serialization you way need. 一种方法是创建自己的Jackson模块并按照您需要的方式进行序列化。

You can even do a simple Jackson8Module which extends the Jackson SimpleModule and provides some lambda friendly methods. 你甚至可以做一个简单的Jackson8Module,它扩展了Jackson SimpleModule并提供了一些lambda友好的方法。

ObjectMapper jacksonMapper = new ObjectMapper();
Jackson8Module module = new Jackson8Module();
module.addStringSerializer(LocalDate.class, (val) -> val.toString());
module.addStringSerializer(LocalDateTime.class, (val) -> val.toString());
jacksonMapper.registerModule(module);

Here is the code for the Jackson8Module: 以下是Jackson8Module的代码:

Is there a way to use Java 8 lambda style to add custom Jackson serializer? 有没有办法使用Java 8 lambda样式添加自定义Jackson序列化程序?

I have found this weird to, since using JSR310Module classes like Calendar or Date are still serialized in milliseconds. 我发现这很奇怪,因为使用JSR310Module类如Calendar或Date仍然以毫秒为单位进行序列化。 It's not logical. 这不符合逻辑。

In the JSR310Module documentation ( https://github.com/FasterXML/jackson-datatype-jsr310 ) they have a referenced this: 在JSR310Module文档( https://github.com/FasterXML/jackson-datatype-jsr310 )中,他们引用了这个:

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. 对于序列化,时间戳写为小数(小数),其中数字为秒,小数为小数秒,如果启用WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS(默认情况下),分辨率可以为纳秒,具体取决于基础JDK实现。 If WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS is disabled, timestamps are written as a whole number of milliseconds. 如果禁用WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS,则将时间戳写为整数毫秒。

So, a simple solution for what you want to achieve it's configure your mapper like they say: 所以,一个简单的解决方案,你想要实现它的配置你的映射器,就像他们说:

  mapper.configure( SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false );
  mapper.configure( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM