Serializing dates as dates and timestamps as timestamps #6139
|
Consider the following out of the box behavior (note that the change of Jackson 3: Jackson 2: Both settings do not result in the desirable outcome of serializing dates as dates and timestamps as timestamps, i. e.
(Haven't checked whether One could define a (de)serializer for each class in question and implement the correct behavior, but I wonder if there is a better/easier/more reliable way that feels less like fighting the out-of-the-box behavior of Jackson? |
Replies: 1 comment 1 reply
|
There is no single representation that Jackson can infer as the semantically correct one here. In particular, For a mixed policy, I would use strings as the general default and configure the exceptions by type: ObjectMapper mapper = JsonMapper.builder()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
mapper.configOverride(Date.class)
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.NUMBER));
mapper.configOverride(GregorianCalendar.class)
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.NUMBER));
mapper.configOverride(Instant.class)
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.NUMBER));
mapper.configOverride(LocalDate.class)
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
mapper.configOverride(LocalTime.class)
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
mapper.configOverride(LocalDateTime.class)
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
mapper.configOverride(ZonedDateTime.class)
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));This centralizes the policy without writing a serializer for every DTO property. Field-level One caveat: numeric The Java-time module documents the array behavior for local types here: https://github.com/FasterXML/jackson-modules-java8/tree/master/datetime#readme |
There is no single representation that Jackson can infer as the semantically correct one here.
WRITE_DATES_AS_TIMESTAMPSis a global representation preference, while the split in the question is a domain-specific, per-type policy.In particular,
LocalDate,LocalTime, andLocalDateTimecannot be converted to an epoch timestamp without supplying a zone/offset. That is why the Java-time module uses arrays for those types when timestamp output is enabled.GregorianCalendar, on the other hand, contains both an instant and a time zone, so it is closer toDate/Instantthan toLocalDateTime.For a mixed policy, I would use strings as the general default and configure the exceptions by type:
Objec…