Efficient way to have Jackson serialize Java 8 Instant as epoch milliseconds? Efficient way to have Jackson serialize Java 8 Instant as epoch milliseconds? angularjs angularjs

Efficient way to have Jackson serialize Java 8 Instant as epoch milliseconds?


You just need to read the README that you linked to. Emphasis mine:

Most JSR-310 types are serialized as numbers (integers or decimals as appropriate) if the SerializationFeature#WRITE_DATES_AS_TIMESTAMPS feature is enabled, and otherwise are serialized in standard ISO-8601 string representation.

[...]

Granularity of timestamps is controlled through the companion features SerializationFeature#WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS and DeserializationFeature#READ_DATE_TIMESTAMPS_AS_NANOSECONDS. 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.


Adding on to JB's answer, to override Spring MVC's default JSON parser to strip away the nanoseconds from Instant (and other Java 8 date objects that have them):

  1. In the mvc:annotation-driven element, specify that you will be overriding the default JSON message converter:

    <mvc:annotation-driven validator="beanValidator"> <mvc:message-converters register-defaults="true"> <beans:ref bean="jsonConverter"/> </mvc:message-converters></mvc:annotation-driven>

(register-defaults above is true by default and most probably what you'll want to keep the other converters configured by Spring as-is).

  1. Override MappingJackson2HttpMessageConverter as follows:

    <beans:bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><beans:property name="objectMapper">    <beans:bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">        <beans:property name="featuresToDisable">            <beans:array>                <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS"/>            </beans:array>        </beans:property>    </beans:bean></beans:property>

Step #1 is important as Spring MVC will otherwise ignore the configured MJ2HMC object in favor of its own default one.

partial H/T this SO post.


A simple way to return epoch millis in the JSON response for an Instant property can be following:

@JsonFormat(shape = JsonFormat.Shape.NUMBER, timezone = "UTC")private Instant createdAt;

This will result in the following response:

{  ...  "createdAt": 1534923249,  ...}