简体   繁体   English

如何从 Jackson ObjectMapper 中排除空对象?

[英]How to exclude empty objects from Jackson ObjectMapper?

Basically I do not want any empty JSON arrays or objects to show up in my generated JSON files.基本上我不希望任何空的 JSON 数组或对象出现在我生成的 JSON 文件中。 I have already configured my ObjectMapper accordingly using the following method:我已经使用以下方法相应地配置了我的 ObjectMapper:

objectMapper.setSerializationInclusion(Include.NON_EMPTY);

This works fine for arrays, collections and Strings.这适用于数组、集合和字符串。 However if i have an empty object (= all properties are null or empty) it will still show up in the generated JSON like this:但是,如果我有一个空对象(= 所有属性为空或为空),它仍会显示在生成的 JSON 中,如下所示:

"MyObject":{}

Here is a possible example of what I mean with an empty object:这是我对空对象的含义的一个可能示例:

class MyClass
{
    String property1 = "";
    Object property2 = null;
}

In this case I want the object to be excluded completely from the generated JSON file.在这种情况下,我希望从生成的 JSON 文件中完全排除对象。

Is this possible?这可能吗? If yes, how to I have to configure my ObjectMapper in order to get the desired behavior?如果是,我必须如何配置我的 ObjectMapper 才能获得所需的行为?

To ignore the empty values such as you may have initialized the arrayList but there are no elements in that list.忽略空值,例如您可能已经初始化了 arrayList 但该列表中没有元素。 In that time using NOT_EMPTY annotation to ignore those empty value fields在那个时候使用 NOT_EMPTY 注释忽略那些空值字段

@JsonInclude(Include.NON_EMPTY)
class Foo
{
  String bar;
}

It's been a few years since the question was asked, but I hit this page looking for a solution.自从提出这个问题已经有几年了,但我点击此页面寻找解决方案。 So here it is.所以在这里。

You need to annotate your class with NON_DEFAULT:你需要用 NON_DEFAULT 注释你的类:

@JsonInclude(NON_DEFAULT)
class MyClass
{
  String property1 = "";
  Object property2 = null;
}

Global config is not enough as explicitly stated in the documentation: http://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonInclude.Include.html#NON_DEFAULT正如文档中明确指出的那样,全局配置是不够的: http : //fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonInclude.Include.html#NON_DEFAULT

The new NON_DEFAULT is available since 2.7新的 NON_DEFAULT 从 2.7 开始可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM