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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With