使用 Jackson 忽略空字段
最后更新: 2013年12月23日
1. 概述
本快速教程将介绍如何设置 Jackson 在序列化 Java 类时忽略空字段。
如果我们想深入了解 Jackson 2 的其他很酷的功能,可以前往 主要的 Jackson 教程。
更多阅读
2. 在类上忽略空字段
Jackson 允许我们在类级别控制此行为
@JsonInclude(Include.NON_NULL)
public class MyDto { ... }
或者在字段级别进行更细粒度的控制
public class MyDto {
@JsonInclude(Include.NON_NULL)
private String stringValue;
private int intValue;
// standard getters and setters
}
现在我们应该能够测试 null 值确实不在最终 JSON 输出中
@Test
public void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored()
throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
MyDto dtoObject = new MyDto();
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}
3. 全局忽略空字段
Jackson 还允许我们 在 ObjectMapper 上全局配置此行为
mapper.setSerializationInclusion(Include.NON_NULL);
现在,通过此 mapper 序列化的任何类的任何 null 字段都将被忽略
@Test
public void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored()
throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
MyDto dtoObject = new MyDto();
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}
4. 结论
忽略 null 字段是一种常见的 Jackson 配置,因为我们通常需要更好地控制 JSON 输出。本文演示了如何对类执行此操作。 然而,还有更高级的用例,例如 在序列化 Map 时忽略 null 值。
支持本文的代码可在 GitHub 上获取。 一旦你以 Baeldung Pro 会员 身份登录,就开始学习并在项目上进行编码。















