I am able to get ZoneDateTime from calling spring rest api. The date that I get in json is in following format:
{
"2017-04-24T15:13:06-05:00"
}
I was able to achieve this in Spring 4 MVC by configuring the following code in ApplicationConfiguration.class:
@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);
}
Now, when i want to send that json date to spring rest for post operation. I am getting following exception:
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
I tried using CustomDeserialization.class and annotating the ZoneDateTime field with @JsonDeserialize(CustomDeserialization.class) but this is also not working.
What is the best way for converting json having date into ZoneDateTime in Spring 4 MVC?
If you want to send a date using JSON, I believe that the simplest way is to first convert the Date into Long type and only then send it as JSON. Something like this:
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;
}
}
and on main method:
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);