首页 > 解决方案 > 反序列化空值时如何让杰克逊库使用我的默认初始化值?

问题描述

我有这个 JSON 输入:

{
    "teachers": null,
    "students": [],
    "janitors": ["J1", "J2"]
}

它将被映射到这个School对象。

public class School {
    
    // Child JSON arrays reflecting JSON input
    private List<String> teachers = new ArrayList<>();
    private List<String> students = new ArrayList<>();
    private List<String> janitors = new ArrayList<>();
    
    // Getters and Setters
    public List<String> getTeachers() {
        return teachers;
    }
    public void setTeachers(List<String> teachers) {
        this.teachers = teachers;
    }

    public List<String> getStudents() {
        return students;
    }
    public void setStudents(List<String> students) {
        this.students = students;
    }

    public List<String> getJanitors() {
        return janitors;
    }
    public void setJanitors(List<String> janitors) {
        this.janitors = janitors;
    }
}

到目前为止,这是我的映射器配置:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

在杰克逊库反序列化 JSON 输入之后,我得到了 School.teachers = null 尽管将其初始化为数组。我初始化这些数组的原因是为了避免不必要的空检查。

如何让 Jackson 反序列化器忽略空值或忽略它无法映射到的空节点?

标签: javajsonjacksondeserialization

解决方案


你可以@JsonInclude(JsonInclude.Include.NON_NULL)在你的课堂上使用。

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class School {
    
    // Child JSON arrays reflecting JSON input
    private List<String> teachers = new ArrayList<>();
    private List<String> students = new ArrayList<>();
    private List<String> janitors = new ArrayList<>();
}

您也可以在现场级别使用它;如果您希望某些字段可以为空。

import com.fasterxml.jackson.annotation.JsonInclude;

public class School {

    // Child JSON arrays reflecting JSON input
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private List<String> teachers = new ArrayList<>();

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private List<String> students = new ArrayList<>();
    
    private List<String> janitors = new ArrayList<>();
}

因此,在上述场景中,如果 janitors 为 null,它将显示为 null。


推荐阅读