首页 > 解决方案 > 杰克逊:没有找到类的序列化器~~~~~也没有找到创建 BeanSerializer 的属性

问题描述

我有一个类的 ArrayList,如下所示:

public class Person {
    String name;
    String age 
    List<String> education = new ArrayList<String> ();
    List<String> family = new ArrayList<String> (); 
    List<String> previousjobs = new ArrayList<String>(); 
}

我想将此列表编写为 Json 并尝试了以下代码:

Writer out = new PrintWriter("./test.json");
mapper.writerWithDefaultPrettyPrinter().writeValueas(out, persons);

并收到此错误消息:

没有找到类~~~~~~的序列化器,也没有发现创建 BeanSerializer 的属性(为避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链:java.util.ArrayList[0])`

我尝试添加mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS),但由于某些未知原因,它使所有人员对象都为空。

我怎么了?

标签: javajsonserializationjackson

解决方案


从这里摘录:

默认情况下,Jackson 2 仅适用于公共字段或具有公共 getter 方法的字段——序列化具有所有字段私有或包私有的实体将失败:

Person的所有字段包都受到保护,并且没有 getter,因此会出现错误消息。禁用消息自然不能解决问题,因为课程仍然empty是杰克逊的观点。这就是为什么您会看到空对象并且最好保留错误。

您需要制作所有字段public,例如:

public class Person {
    public String name;
    // rest of the stuff...
}

或为每个字段创建一个公共 getter(最好也将字段设置为私有),例如:

public class Person {
    private String name;

    public String getName() {
        return this.name;
    }
    // rest of the stuff...
}

推荐阅读