我可以通过调用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 for post操作时。我得到以下例外:
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的最佳方法是什么?
答案 0 :(得分:-1)
如果你想使用JSON发送日期,我相信最简单的方法是先将Date转换为Long类型,然后再将其作为JSON发送。像这样:
public class MyJson {
Long date;
public MyJson() {
}
public MyJson(Long date) {
this.date = date;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
}
以及主要方法:
Date date = new Date();
MyJson json = new MyJson(date.getTime());
ObjectMapper objectMapper = new ObjectMapper();
String strJson = objectMapper.writeValueAsString(json);
MyJson result = objectMapper.readValue(strJson, MyJson.class);