Home > database >  Unable to serialize/deserialize ZonedDateTime correctly using jackson
Unable to serialize/deserialize ZonedDateTime correctly using jackson

Time:12-12

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]

CodePudding user response:

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

CodePudding user response:

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);
  • Related