java - 反序列化空值时如何让杰克逊库使用我的默认初始化值?
问题描述
我有这个 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 反序列化器忽略空值或忽略它无法映射到的空节点?
解决方案
你可以@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。
推荐阅读
- android - 仅在需要时调整文本视图文本大小以适合文本视图大小
- node.js - 在使用 MessageCollector 达到设置的时间限制后如何触发代码?
- php - 来自popen的PHP pid
- firebase - 由于我的应用程序使用密码身份验证,因此上面的代码将在该字段中给我 null
- azure - 如何在 Azure 托管应用程序 ARM 部署中强制选择服务主体
- c# - 如何仅获取 C# 中两个 DateTimeOffset 之间的时间差,而忽略日期差?
- c++ - std::mutex 的 constexpr 构造函数是如何实现的?
- firebase - Firebase 身份验证 Google 登录以仅允许特定的 google 工作区帐户
- linux - X11 监听嵌套窗口的光标样式更新(chrome)
- c++ - GetProcAddress 在 DLL 中找不到函数