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

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

    If you are using ObjectMapper class of fasterxml, by default ObjectMapper do not understand the LocalDateTime class, so, you need to add another dependency in your gradle/maven :

    compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.7.3'
    

    Now you need to register the datatype support offered by this library into you objectmapper object, this can be done by following :

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    

    Now, in your jsonString, you can easily put your java.LocalDateTime field as follows :

    {
        "user_id": 1,
        "score": 9,
        "date_time": "2016-05-28T17:39:44.937"
    }
    

    By doing all this, your Json file to Java object conversion will work fine, you can read the file by following :

    objectMapper.readValue(jsonString, new TypeReference>() {
                });
    

提交回复
热议问题