【问题标题】:How do I get Jackson library to use my default initialized value when deserializing null value?反序列化空值时,如何让 Jackson 库使用我的默认初始化值?
【发布时间】:2021-09-07 18:16:52
【问题描述】:

我有这个 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);

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

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

【问题讨论】:

    标签: java json jackson deserialization


    【解决方案1】:

    您可以在课堂上使用@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。

    【讨论】:

    • 它适用于序列化,而不适用于反序列化
    猜你喜欢
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    相关资源
    最近更新 更多