Jackson LocalDate 模块注册仍然异常

Jackson LocalDate module registered still exception

我想用 class Personfirstnamelastnamebirthday 的不同对象序列化列表。在查看论坛中的不同问题后,我发现我需要注册 jsr.310.JavaTimeModule 才能序列化 LocalDate birthday。我知道这个网站上有很多关于这个主题的条目,但大多数都说注册模块足以处理 LocalDate

这是我的作家class:

public void write(){
    ArrayList<Person> personList = new ArrayList<>();

    Person p1 = new Person("Peter", "Griffin", LocalDate.of(1988,6,5));
    Person p2 = new Person("Lois", "Griffin", LocalDate.of(1997,9,22));

    personList.add(p1);
    personList.add(p2);

    ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
    ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());

    try {
        writer.writeValue(new File(System.getProperty("user.dir")+"/File/Personen.json"), personList);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我的 Reader class 是:

 public void read(){
    ObjectMapper mapper = new ObjectMapper();

    try {
        ArrayList<Person> liste = mapper.readValue(new FileInputStream("File/Personen.json"),
                mapper.getTypeFactory().constructCollectionType(ArrayList.class, Person.class));
        System.out.println(liste.get(0).getFirstname());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

阅读文件后我得到一个

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('1988-06-05')
at [Source: (FileInputStream); line: 4, column: 18] (through reference chain: java.util.ArrayList[0]->Person["birthday"])

我认为我不需要做任何比注册 TimeModule 更重要的事情。我还需要为 reader 注册一个模块吗?还是我的代码有其他问题?

您正确地注册了 JavaTimeModule ObjectMapper 在你的 write() 方法中。

ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());

但是你忘了在你的read()方法中用ObjectMapper注册它。

ObjectMapper mapper = new ObjectMapper();

要修复它,只需在此处添加缺少的 .registerModule(new JavaTimeModule())

或者更好:
writeread 方法中删除本地 ObjectMapper 定义。 相反,将它作为成员变量添加到您的 class,以便您可以使用 两种方法中的相同 ObjectMapper 实例。

private ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());