Ambi
Ambi

Reputation: 503

Jackson ignore empty objects "{}" without custom serializer

I would like to serialize to JSON a POJO containing another POJO with empty values.

For example, given:

class School {
  String name;
  Room room;
}

class Room {
  String name;
}

Room room = new Room();
School school = new School("name");
school.room = room;

After the serialisation it will look like that

{ "name": "name", "room": {}}

Is it possible to exclude the empty object {} if all the fields of the class are also empty? Ideally globally for every object without writing custom code.

Upvotes: 14

Views: 14666

Answers (2)

Miguel Galindo
Miguel Galindo

Reputation: 121

A little bit late , add JsonInclude custom

class School {
  String name;
  @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = Room .class)
  Room room;
}


@EqualsAndHashCode
class Room {
      String name;
}

This will avoid to include room if is equals than new Room(). Don't forget implement equals method in Room class and include an empty constructor

Besides you can use @JsonInclude( Include.NON_EMPTY ) or @JsonInclude( Include.NON_DEFAULT ) at class level to skip possible nulls or empty values

Upvotes: 8

shakel
shakel

Reputation: 217

TLDR: the behavior you want won't work because the Object has been instantiated, needs to be null.


Include.NON_EMPTY
Include.NON_NULL

The reason these options don't work with what you are trying to do is because you have instantiated an Object of Room type so Room is not empty or null hence your output: { "name": "name", "room": {}}

If you effectively want to avoid having Room represented in your JSON, then the Object needs to be null. By setting school.room = null you would get your desired output, though in the real world this could become messy as you'd have to evaluate if fields in the Object were actually null before setting Room in School to be null.

A custom serializer would handle this better, see: Do not include empty object to Jackson

Upvotes: 4

Related Questions