忽略空值字段(Jackson)

Data,Jackson
Remote
0
01:18 AM · Dec 01 ,2025

1. 概述

本快速教程將介紹如何設置 Jackson 在序列化 Java 類時忽略 null 字段

如果想要深入學習更多關於 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;

    // 標準的 getter 和 setter
}

現在我們應該能夠測試 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 值。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.