zjffdu
zjffdu

Reputation: 28944

Unable to serialize/deserialize ZonedDateTime correctly using jackson

I'd like to serialize/deserialize ZonedDateTime in my spring boot app, so I need to customise the ObjectMapper. But when I deserialize it back, I can not get the ZonedDateTime correctly.

Here's my sample code:

ObjectMapper mapper = new ObjectMapper()
    .enable(MapperFeature.DEFAULT_VIEW_INCLUSION)
    .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
    .findAndRegisterModules();

ZonedDateTime dateTime = ZonedDateTime.now();
String json = mapper.writeValueAsString(dateTime);
LOGGER.info("ZonedDateTime json: " + json);

ZonedDateTime dateTime2 = mapper.readValue(json, ZonedDateTime.class);
assertEquals(dateTime, dateTime2);

This test fails with following:

org.opentest4j.AssertionFailedError: 
Expected :2022-12-12T18:00:48.711+08:00[Asia/Shanghai]
Actual   :2022-12-12T10:00:48.711Z[UTC]

Upvotes: 0

Views: 2779

Answers (2)

zjffdu
zjffdu

Reputation: 28944

Sorry folks, it seems my fault. I should specify the zoneId when creating ZonedDateTime.

The following code pass:

ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("UTC"));
String json = mapper.writeValueAsString(dateTime);
LOGGER.info("ZonedDateTime json: " + json);

ZonedDateTime dateTime2 = mapper.readValue(json, ZonedDateTime.class);
assertEquals(dateTime, dateTime2);

Upvotes: 1

Michael Gantman
Michael Gantman

Reputation: 7808

You don't need to customize ObjectMapper. Try to add this annotation above your property:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
ZonedDateTime myDate

For more details look at this question and the accepted answer: Spring Data JPA - ZonedDateTime format for json serialization

Upvotes: 0

Related Questions