I have an issue where my RestTemplate.postForEntity(url, restRequest, RepoResponse.class)
call is failing because it can't deserialise dates of the form:
- 2019-02-01T12:00:00.000-0500
because of the missing colon in the timezone.
Based on this answer, it looks like I want to change the date formatting of my RestTemplate
's ObjectMapper
.
I've tried a solution here: https://stackoverflow.com/a/38286322/14250
Which gives me the following code:
restTemplate = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS[XXX][X]");
objectMapper.setDateFormat(format);
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setPrettyPrint(false);
messageConverter.setObjectMapper(objectMapper);
restTemplate.getMessageConverters().removeIf(m->m.getClass().getName().equals(MappingJackson2HttpMessageConverter.class.getName()));
restTemplate.getMessageConverters().add(messageConverter);
Unfortunately I get the following error
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.OffsetDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-02-13T12:33:19.179-0500')
Is there an easy way to make RestTemplate support the above datetime format?
When you are working with java.time.*
classes and Jackson
is good to start from registering JavaTimeModule
which comes from jackson-datatype-jsr310 module.
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.OffsetDateTime;
public class JsonApp {
public static void main(String[] args) throws Exception {
JavaTimeModule javaTimeModule = new JavaTimeModule();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(javaTimeModule);
String json = "{\"now\":\"2019-02-01T12:01:01.001-0500\"}";
System.out.println(mapper.readValue(json, Time.class));
}
}
class Time {
@JsonFormat(pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSX")
private OffsetDateTime now = OffsetDateTime.now();
public OffsetDateTime getNow() {
return now;
}
public void setNow(OffsetDateTime now) {
this.now = now;
}
@Override
public String toString() {
return "PrintObject{" +
"now=" + now +
'}';
}
}
Above code prints:
PrintObject{now=2019-02-01T17:01:01.001Z}
来源:https://stackoverflow.com/questions/54676382/how-do-i-update-resttemplate-to-correctly-map-java-dates