Jackson ignore empty objects "{}" without custom serializer

2022-09-04 22:51:23

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.{}


答案 1

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 . Don't forget implement equals method in Room class and include an empty constructornew Room()

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


答案 2

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 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.school.room = null

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