Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson ignore empty objects "{}" without custom serializer

Tags:

java

json

jackson

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.

like image 656
Ambi Avatar asked Dec 20 '18 12:12

Ambi


People also ask

How do I ignore null values in Jackson?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL. Let's take an example to understand how we can use @JsonInclude annotation to ignore the null fields at the class level.

How do you tell Jackson to ignore a field during serialization?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

How do I ignore JSON property?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

How do I ignore properties in ObjectMapper?

ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); objectMapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false); This will now ignore unknown properties for any JSON it's going to parse, You should only use this option if you can't annotate a class with @JsonIgnoreProperties annotation.


1 Answers

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

like image 128
Miguel Galindo Avatar answered Sep 26 '22 08:09

Miguel Galindo