Contents

Jackson 忽略空字段

1. 概述

本快速教程将介绍如何设置Jackson 在序列化java 类时忽略空字段。

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

现在通过这个映射器序列化的任何类中的任何字段都将被忽略:

@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")));
}