Puedo obtener ZoneDateTime llamando a Spring Rest API. La fecha que obtengo en json tiene el siguiente formato:
{ "2017-04-24T15:13:06-05:00" }Pude lograr esto en Spring 4 MVC configurando el siguiente código en 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); }Ahora, cuando quiero enviar esa fecha json a Spring Rest para la operación posterior. Recibo la siguiente excepción:
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 19Intenté usar CustomDeserialization.class y anotar el campo ZoneDateTime con @JsonDeserialize(CustomDeserialization.class) pero esto tampoco funciona.
¿Cuál es la mejor manera de convertir json con fecha en ZoneDateTime en Spring 4 MVC?
Si desea enviar una fecha usando JSON, creo que la forma más sencilla es convertir primero la fecha en tipo largo y luego enviarla como JSON. Algo como esto:
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; } }y en el método principal:
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);