I'm moving from using java.sql.Timestamp
and java.util.GregorianCalendar
to employ java.time.*
new classes in a Spring MVC application.
So I changed every
private GregorianCalendar field;
to
private LocalDate field;
or
private LocalDateTime field;
But now when serializing those beans, they get serialized like this:
"field": {
"year": 1970,
"month": "JANUARY",
"dayOfMonth": 18,
"dayOfWeek": "SUNDAY",
"era": "CE",
"dayOfYear": 18,
"leapYear": false,
"monthValue": 1,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
},
I found answers to other questions that mention to add a dependency to jackson-datatype-jsr310 and obtained:
"field": [
1970,
1,
18
],
but I still want a unix timestamp when serializing like I got with GregorianCalendar
fields: how can I achieve that? Can I avoid a custom serializer (and deserializer)?
These are relevant for resource responses and request bodies (as in POST, PUT, etc), not for request parameters.
The Jackson ObjectMapper
is configured like so:
jacksonConverter.getObjectMapper().enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
jacksonConverter.getObjectMapper().disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
In the JavaDoc to JavaTimeModule (included in
jackson-datatype-jsr310
library), we can read the following:and then:
You can indeed see that
LocalDateTime
cannot be ubiquitously converted to the Unix timestamp because its toEpochSecond method takesZoneOffset
as parameter.To sum up, it seems the best thing you can do is replacing
LocalDateTime
withInstant
(see this great answer for an explanation of the difference betweenLocalDateTime
andInstant
).Other than that, you would indeed need custom
JsonSerializer
andJsonDeserializer
.Here's a working code sample: