How do I update RestTemplate to correctly map Java Dates?

橙三吉。 提交于 2019-12-02 04:12:07

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}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!