How would you correctly serialize and deserialize java.time types (like LocalDateTime or ZonedDateTime) to/from JSON using a library like Jackson, and what common configuration pitfalls arise?
Short answer
Jackson requires the jackson-datatype-jsr310 module (registered via objectMapper.registerModule(new JavaTimeModule())) to properly support java.time types, since Jackson's core doesn't have built-in support for them out of the box -- a common pitfall is Jackson's default…
Advertisement
AModel answer
Jackson requires the jackson-datatype-jsr310 module (registered via objectMapper.registerModule(new JavaTimeModule())) to properly support java.time types, since Jackson's core doesn't have built-in support for them out of the box -- a common pitfall is Jackson's default behavior of serializing date/time values as numeric timestamp arrays or epoch values rather than a more universally readable ISO-8601 string format, addressed by disabling SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, and additionally, ZonedDateTime specifically needs careful attention to ensure its timezone information is actually preserved through the serialization round-trip rather than silently lost or normalized to UTC unexpectedly.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule()); // required for java.time support at all
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // use readable ISO-8601 strings instead of raw arrays
public class Event {
private ZonedDateTime startTime;
// getters/setters
}
String json = mapper.writeValueAsString(event);
// Produces: {"startTime":"2024-06-01T14:30:00-04:00[America/New_York]"} -- readable, timezone-preserving ISO formatReal-world example
An API initially serializing LocalDateTime fields as confusing numeric arrays (like [2024,6,1,14,30,0]) due to Jackson's default timestamp-array behavior switches to disabling WRITE_DATES_AS_TIMESTAMPS, producing much more universally readable and interoperable ISO-8601 formatted date strings in its JSON responses instead.
Likely follow-ups
- Why doesn't Jackson support java.time types out of the box, requiring a separate module registration?
- What's the specific JSON format difference between serializing a ZonedDateTime versus an Instant, and why does that difference matter for API consumers?
Related topics