0

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]
zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • Does this answer your question? [Spring Data JPA - ZonedDateTime format for json serialization](https://stackoverflow.com/questions/31627992/spring-data-jpa-zoneddatetime-format-for-json-serialization) – Michael Gantman Dec 12 '22 at 10:11
  • It seems it is the same as my above example code, the above assert statement still fails. – zjffdu Dec 12 '22 at 11:54

2 Answers2

1

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);
zjffdu
  • 25,496
  • 45
  • 109
  • 159
0

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

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • It doesn't work for me, because there're many places using ZonedDateTime, I don't want to add annotation everywhere, I just want to configure it globally. – zjffdu Dec 12 '22 at 11:53