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

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

    Update: Leaving this answer for historical reasons, but I don't recommend it. Please see the accepted answer above.

    Tell Jackson to map using your custom [de]serialization classes:

    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    private LocalDateTime ignoreUntil;
    

    provide custom classes:

    public class LocalDateTimeSerializer extends JsonSerializer {
        @Override
        public void serialize(LocalDateTime arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException {
            arg1.writeString(arg0.toString());
        }
    }
    
    public class LocalDateTimeDeserializer extends JsonDeserializer {
        @Override
        public LocalDateTime deserialize(JsonParser arg0, DeserializationContext arg1) throws IOException {
            return LocalDateTime.parse(arg0.getText());
        }
    }
    

    random fact: if i nest above classes and don't make them static, the error message is weird: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported

提交回复
热议问题