TempGo
发布于 2025-10-19 / 10 阅读
0
0

Jackson如何配置忽略空字段

1. 概述

本文快速介绍如何在序列化 Java 类时配置 Jackson 忽略为 null 的字段。

如果想进一步学习 Jackson 2 的更多用法,可以参考主教程。

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);

通过该设置,任何类中为 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 值。


评论