我想在我的spring boot应用中序列化/反序列化ZonedDateTime,所以我需要自定义ObjectMapper。但是当我反序列化它回来时,我不能正确地获得ZonedDateTime。
下面是我的示例代码:
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);
本测试失败,原因如下:
org.opentest4j.AssertionFailedError:
Expected :2022-12-12T18:00:48.711+08:00[Asia/Shanghai]
Actual :2022-12-12T10:00:48.711Z[UTC]
2条答案
按热度按时间3npbholx1#
对不起,朋友们,这似乎是我的错。我应该在创建ZonedDateTime时指定zoneId。
以下代码通过:
hvvq6cgz2#
不需要自定义ObjectMapper。请尝试在属性上方添加此注解:
有关详细信息,请查看此问题和公认答案:Spring Data JPA - ZonedDateTime format for json serialization