Jackson Java 8 DateTime serialisation
Solution 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?
Solution 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 );
Andrii Karaivanskyi
Updated on June 04, 2022Comments
-
Andrii Karaivanskyi almost 2 years
Jackson operates java.time.Instant with
WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS
(READ_
as well) enabled by default. jackson-datatype-jsr310It 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?
-
Ruslan Stelmachenko over 5 years
WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS
is really confusing name because what it really does: it writes timestamps as SECONDS (not NANOSECONDS) with fractional part. And that fractional part contains up to 6 digits after dot, so it can be interpreted as NANOSECONDS part, but the whole value is still in seconds. -
veritas over 3 yearsmapper.configure() - where should this be done? Do you know how to do this in XML?