【发布时间】:2025-12-03 20:50:01
【问题描述】:
我可以通过调用 spring rest api 来获取 ZoneDateTime。我在 json 中得到的日期格式如下:
{
"2017-04-24T15:13:06-05:00"
}
通过在 ApplicationConfiguration.class 中配置以下代码,我能够在 Spring 4 MVC 中实现这一点:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.registerModule(new JavaTimeModule());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper);
converters.add(converter);
}
现在,当我想将该 json 日期发送到 spring rest 以进行后期操作时。我收到以下异常:
WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of java.time.ZonedDateTime from String value ("2017-04-24T15:13:06-05:00"): Text '2017-04-24T15:13:06-05:00' could not be parsed at index 19
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.time.ZonedDateTime from String value ("2017-04-24T15:13:06-05:00"): Text '2017-04-24T15:13:06-05:00' could not be parsed at index 19
我尝试使用 CustomDeserialization.class 并使用 @JsonDeserialize(CustomDeserialization.class) 注释 ZoneDateTime 字段,但这也不起作用。
在 Spring 4 MVC 中将具有日期的 json 转换为 ZoneDateTime 的最佳方法是什么?
【问题讨论】:
-
首先应该是什么区域?有多个时区具有 -05:00 偏移量。应该选择哪一个?为什么要将看起来不像分区日期时间的内容反序列化为分区日期时间?
-
我在实体类中有一个 createdDate 字段,它作为 ZoneDateTime 存储在数据库中。我只是想发送 ZoneDateTime 的 json 字符串并将其存储在数据库中。通过使用 ObjectMapper,我能够从数据库中获取 ZoneDateTime,但无法使用发布请求发送。
标签: java json spring-mvc