Andrii Karaivanskyi
Andrii Karaivanskyi

Reputation: 2002

Jackson Java 8 DateTime serialisation

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?

Upvotes: 2

Views: 11978

Answers (2)

Pedro Sequeira
Pedro Sequeira

Reputation: 332

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

Upvotes: 5

Jeremy Chone
Jeremy Chone

Reputation: 3157

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?

Upvotes: 5

Related Questions