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;
// 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 值。