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

后端 未结 17 1381
隐瞒了意图╮
隐瞒了意图╮ 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:36

    This is just an example how to use it in a unit test that I hacked to debug this issue. The key ingredients are

    • mapper.registerModule(new JavaTimeModule());
    • maven dependency of jackson-datatype-jsr310

    Code:

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
    import org.testng.Assert;
    import org.testng.annotations.Test;
    
    import java.io.IOException;
    import java.io.Serializable;
    import java.time.Instant;
    
    class Mumu implements Serializable {
        private Instant from;
        private String text;
    
        Mumu(Instant from, String text) {
            this.from = from;
            this.text = text;
        }
    
        public Mumu() {
        }
    
        public Instant getFrom() {
            return from;
        }
    
        public String getText() {
            return text;
        }
    
        @Override
        public String toString() {
            return "Mumu{" +
                    "from=" + from +
                    ", text='" + text + '\'' +
                    '}';
        }
    }
    public class Scratch {
    
    
        @Test
        public void JacksonInstant() throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new JavaTimeModule());
    
            Mumu before = new Mumu(Instant.now(), "before");
            String jsonInString = mapper.writeValueAsString(before);
    
    
            System.out.println("-- BEFORE --");
            System.out.println(before);
            System.out.println(jsonInString);
    
            Mumu after = mapper.readValue(jsonInString, Mumu.class);
            System.out.println("-- AFTER --");
            System.out.println(after);
    
            Assert.assertEquals(after.toString(), before.toString());
        }
    
    }
    

提交回复
热议问题