简体   繁体   中英

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. I have already configured my ObjectMapper accordingly using the following method:

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:

"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.

Is this possible? If yes, how to I have to configure my ObjectMapper in order to get the desired behavior?

To ignore the empty values such as you may have initialized the arrayList but there are no elements in that list. In that time using NOT_EMPTY annotation to ignore those empty value fields

@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:

@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

The new NON_DEFAULT is available since 2.7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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