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:
Most java.time
types are serialized as numbers (integers or decimals as appropriate) if the SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
feature is enabled [...]
[...] If SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS
is disabled, timestamps are written as a whole number of milliseconds. [...]
and then:
Some exceptions to this standard serialization/deserialization rule:
- [...]
LocalDate
, LocalTime
, LocalDateTime
, and OffsetTime
, which cannot portably be converted to timestamps and are instead represented as arrays when WRITE_DATES_AS_TIMESTAMPS
is enabled.
You can indeed see that LocalDateTime
cannot be ubiquitously converted to the Unix timestamp because its toEpochSecond method takes ZoneOffset
as parameter.
To sum up, it seems the best thing you can do is replacing LocalDateTime
with Instant
(see this great answer for an explanation of the difference between LocalDateTime
and Instant
).
Other than that, you would indeed need custom JsonSerializer
and JsonDeserializer
.
Here's a working code sample:
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
Entity entity = new Entity(Instant.now());
StringWriter writer = new StringWriter();
objectMapper.writeValue(writer, entity);
System.out.println(writer.getBuffer());
}
@lombok.Value
static class Entity {
Instant timestamp;
}