Spring Jackson java.time反序列化:参数不匹配

时间:2017-12-05 18:12:02

标签: json spring java-8 jackson

如何反序列化Java 8时间API类?

这就是我所做的:

包含依赖项:compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

请求将序列反序列化为:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.joda.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;

public class TestRequest {
    @JsonSerialize(using = LocalDateSerializer.class)
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "YYYY-MM-dd")
    LocalDate localDate;
}

Spring Controller:

public ResponseEntity test(@RequestBody TestRequest testRequest) {
    return ResponseEntity.ok(testRequest);
}

JSON请求正文:

{ "localDate": "2017-11-01" }

例外:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of TestRequest, problem: argument type mismatch

1 个答案:

答案 0 :(得分:1)

您应该使用jackson-modules-java8而不是jackson-datatype-jsr310来序列化或反序列化java 8类。