使用jackson从json中删除空值 [英] Remove null values from json using jackson
问题描述
我正在尝试从我的json中删除所有空值。
I am trying to remove all the null values from my json.
{
"key" : null
}
我用过:
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
这里key是一个列表,所以当我使用上面的序列化选项时,json会被转换至:
Here "key" is a list and so when I use the above serialization option, the json gets converted to:
{
"key" : []
}
我希望json为:
{
}
我不想使用
Include.NON_EMPTY
因为我在我的项目中有其他json,我需要显示空列表和0值键。当它是一个列表时,有没有办法删除空值键,就像它对字符串值一样?
as I have other json in my project where I need to show the empty list and 0 valued keys. Is there any way to remove the null valued keys when it is a list, the same way it does for a string value?
我不能使用注释,因为类文件是使用jaxb从xml生成。类结构:
I cannot use annotations as the class files are being generated from xml using jaxb. Class Structure:
public class C1 {
protected List<C2> key;
public List<C2> getKey() {
if (key == null) {
key = new ArrayList<C2>();
}
return this.key;
}
}
我被困了一段时间现在。任何帮助都非常感谢。在此先感谢。
I have been stuck for a while now. Any help is highly appreciated. Thanks in advance.
推荐答案
要禁止使用 null
值序列化属性,
To suppress serializing properties with null
values,
您可以直接使用此配置 ObjectMapper
。
you can configure the ObjectMapper
directly using this.
mapper.setSerializationInclusion(Include.NON_NULL);
这篇关于使用jackson从json中删除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!