serialize/deserialize java 8 java.time with Jackson JSON mapper

后端 未结 17 1150
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 15:56

How do I use Jackson JSON mapper with Java 8 LocalDateTime?

org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple t

17条回答
  •  名媛妹妹
    2020-11-22 16:57

    If you can't use jackson-modules-java8 for whatever reasons you can (de-)serialize the instant field as long using @JsonIgnore and @JsonGetter & @JsonSetter:

    public class MyBean {
    
        private Instant time = Instant.now();
    
        @JsonIgnore
        public Instant getTime() {
            return this.time;
        }
    
        public void setTime(Instant time) {
            this.time = time;
        }
    
        @JsonGetter
        private long getEpochTime() {
            return this.time.toEpochMilli();
        }
    
        @JsonSetter
        private void setEpochTime(long time) {
            this.time = Instant.ofEpochMilli(time);
        }
    }
    

    Example:

    @Test
    public void testJsonTime() throws Exception {
        String json = new ObjectMapper().writeValueAsString(new MyBean());
        System.out.println(json);
        MyBean myBean = new ObjectMapper().readValue(json, MyBean.class);
        System.out.println(myBean.getTime());
    }
    

    yields

    {"epochTime":1506432517242}
    2017-09-26T13:28:37.242Z
    

提交回复
热议问题