15

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.

Ambi
  • 513
  • 1
  • 6
  • 18

3 Answers3

8

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

Miguel Galindo
  • 111
  • 1
  • 3
  • this requires using Jackson 2.9+ as `JsonInclude.Include.CUSTOM` isn't available in earlier versions – Mr.Cat Feb 14 '22 at 12:39
3

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

shakel
  • 207
  • 3
  • 13
-2

Add @JsonInclude(Include.NON_EMPTY) to remove empty objects:

@JsonInclude(Include.NON_EMPTY)
class School {

Value that indicates that only properties with non-null values are to be included.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • 1
    It will work if school.room is null but it's not null – xyz Dec 20 '18 at 13:00
  • I tried that already, but it doesn't work. The documentation states that this works for Collections, Maps, Arrays and Strings. My `Room` class though, has an instance, despite having all fields as null, so it will be included in the output @user7294900 – Ambi Dec 20 '18 at 13:20
  • @Ambi Try `@JsonInclude(Include.NON_EMPTY)` to class `Room` also – Ori Marko Dec 20 '18 at 13:23
  • Not working either, in line with what the documentation says. – Ambi Dec 21 '18 at 10:34