Jackson Java 8 DateTime serialisation

Andrii Karaivanskyi picture Andrii Karaivanskyi · Jan 14, 2015 · Viewed 9.8k times · Source

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?

Answer

Jeremy Chone picture Jeremy Chone · Jan 26, 2015

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?