Ignore Null Fields with Jackson – 用Jackson忽略空字段

最后修改: 2013年 12月 23日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This quick tutorial is going to cover how to set up Jackson to ignore null fields when serializing a java class.

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

If we want to dig deeper and learn other cool things to do with the Jackson 2, we can head on over to the main Jackson tutorial.

如果我们想更深入地挖掘和学习使用杰克逊2的其他很酷的事情,我们可以前往杰克逊主要教程

2. Ignore Null Fields on the Class

2.忽略类上的空字段

Jackson allow us to control this behavior at either the class level:

Jackson允许我们在类的层面上控制这种行为:

@JsonInclude(Include.NON_NULL)
public class MyDto { ... }

Or with more granularity at the field level:

或者在领域层面上有更多的细化:

public class MyDto {

    @JsonInclude(Include.NON_NULL)
    private String stringValue;

    private int intValue;

    // standard getters and setters
}

Now we should be able to test that null values are indeed not part of the final JSON output:

现在我们应该能测试出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. Ignore Null Fields Globally

3.全局性地忽略空字段

Jackson also allows us to configure this behavior globally on the ObjectMapper:

Jackson还允许我们ObjectMapper上全局配置这种行为。

mapper.setSerializationInclusion(Include.NON_NULL);

Now any null field in any class serialized through this mapper is going to be ignored:

现在,通过这个映射器序列化的任何类中的任何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. Conclusion

4.结论

Ignoring null fields is such a common Jackson configuration because it’s often the case that we need to have better control over the JSON output. This article demonstrates how to do that for classes. There are, however, more advanced use cases, such as ignoring null values when serializing a Map.

忽略null字段是如此常见的Jackson配置,因为我们经常需要对JSON输出进行更好的控制。这篇文章演示了如何为类做这件事。然而,还有一些更高级的用例,例如序列化 Map 时忽略空值

The implementation of all of these examples and code snippets can be found in the Github project.

所有这些例子和代码片段的实现都可以在Github项目中找到。