首页 > 解决方案 > Jackson LocalDate 模块注册仍然异常

问题描述

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

这是我的作家课:

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();
    }
}

我的阅读器课程是:

 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:无法构造 java.time.LocalDate 的实例(没有创建者,如默认构造,存在):没有从字符串值反序列化的字符串参数构造函数/工厂方法('1988-06 -05')
在 [来源: (FileInputStream); 行:4,列:18](通过引用链:java.util.ArrayList[0]->Person["birthday"])

我以为除了注册TimeModule. 我还需要为阅读器注册一个模块吗?还是我的代码有其他问题?

标签: javajsonserializationjacksonlocaldate

解决方案


您在您的方法中正确注册了JavaTimeModuleObjectMapperwrite()

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

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

ObjectMapper mapper = new ObjectMapper();

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

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

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

推荐阅读