提问者:小点点

通用域名格式。fasterxml。杰克逊。数据绑定。exc.InvalidDefinitionException:无法构造'java'的实例。时间本地日期


将字符串反序列化为对象时遇到错误。

org.opentest4j.MultipleFailuresError:多个失败(2失败)com.fasterxml.jackson.databind.exc.Invalid定义异常:无法构建java.time.LocalDate的实例(没有Creator,像默认构造一样,存在):没有String-参数构造函数/工厂方法从String值反序列化('2020-05-20')at[来源:(字符串)

JSON

 {
       "studentId":57,
       "JoinedDate":"31-12-2019",
       "DOB":"08-06-1998"  

    }

模型

public class Student{

    private long studentId ;

    private LocalDate JoinedDate;

    private LocalDate DOB ;

    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public LocalDate getJoinedDate() {
        return JoinedDate;
    }

    public void setJoinedDate(LocalDate joinedDate) {
        JoinedDate = joinedDate;
    }

    public LocalDate getDOB() {
        return DOB;
    }

    public void setDOB(LocalDate dOB) {
        DOB = dOB;
    }

单元测试课

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public class StudentTest{


private Student student;
private ObjectMapper jsonObjectMapper;
@Before
public void setUp() throws IOException {

    jsonObjectMapper = new ObjectMapper();
    jsonObjectMapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
    studentJson = IOUtils.toString(getClass().getResourceAsStream(CommonTestConstants.StudentPath+ "/Student.json"));


student = jsonObjectMapper.readValue(studentJson , Student.class);
}

有人请指教

引用无法构造'java'的实例。时间ZoneDateTime`(不存在像默认构造这样的创建者)

无法反序列化-Jackson LocalDate/Time-JUnit


共1个答案

匿名用户

  1. 包括jsr310模块。
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.11.0</version>
</dependency>
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
@JsonFormat(pattern = "dd-MM-yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)

完整的代码是:

主类或jUnit:

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        Student student = objectMapper.readValue(YOUR_JSON_STRING, Student.class);
        System.out.println(student);
    }

学生:

public class Student {

    private long studentId;

    @JsonProperty("JoinedDate")
    @JsonFormat(pattern = "dd-MM-yyyy")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate JoinedDate;

    @JsonFormat(pattern = "dd-MM-yyyy")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate DOB;

    // getters and setters and ToString
}

相关问题