原文链接:Ignore Null Fields with Jackson
1. Overview 概述
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.
如果想进一步深入了解Jackson2,可以点击 the main Jackson tutorial
2. Ignore Null Fields on the Class 在Java类中忽略空值属性
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:
接着来测试下吧,看看空的属性值最终是否会被解析输出,代码如下:
@Test
public void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored()
throws JsonProcessingException {
// 对象映射
ObjectMapper mapper = new ObjectMapper();
// 要序列化的数据对象
MyDto dtoObject = new MyDto();
// 序列化对象到JSON
String dtoAsString = mapper.writeValueAsString(dtoObject);
// 判断是不正确忽略空值属性
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}
3. Ignore Null Fields Globally 全局性的忽略空值属性
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:
加入上面代码,所有的空值属性在序列化时就会被忽略掉了
@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 最后
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.
为了更好的控制JSON的输出内容,我们通过配置公共的Jackson参数来忽略空值属性,这篇文章示范了如何实现。不过有更多的使用案例,如序列化Map时忽略空值属性,点击 这里 查看
大家关注点赞哈