How do I update RestTemplate to correctly map Java Dates?

前端 未结 1 462
感动是毒
感动是毒 2021-01-21 13:34

I have an issue where my RestTemplate.postForEntity(url, restRequest, RepoResponse.class) call is failing because it can\'t deserialise dates of the form:

相关标签:
1条回答
  • 2021-01-21 13:51

    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}
    
    0 讨论(0)
提交回复
热议问题