Jackson Java 8 DateTime serialisation

▼魔方 西西 提交于 2020-01-04 17:51:10

问题


Jackson operates java.time.Instant with WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS (READ_ as well) enabled by default. jackson-datatype-jsr310

It produces JSON like this

{ "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).

I think there should be some reason to have the nanos approach by default, so what is that reason?


回答1:


One way is to create your own Jackson module and do the serialization you way need.

You can even do a simple Jackson8Module which extends the Jackson SimpleModule and provides some lambda friendly methods.

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:

Is there a way to use Java 8 lambda style to add custom Jackson serializer?




回答2:


I have found this weird to, since using JSR310Module classes like Calendar or Date are still serialized in milliseconds. It's not logical.

In the JSR310Module documentation (https://github.com/FasterXML/jackson-datatype-jsr310) they have a referenced this:

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.

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 );


来源:https://stackoverflow.com/questions/27951124/jackson-java-8-datetime-serialisation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!