Effectively ignore nested properties in Spring Boot using Jackson
We have the following options for effectively ignore nested properties.
@JsonIgnoreProperties
Recursively
This is the most straightforward way, but you must annotate each class in the hierarchy where you want to ignore properties.
This approach requires us to annotate each nested class.
@Data
@JsonIgnoreProperties({"name"})
class University {
private int id;
private String name;
private String address;
private Student student;
}
@Data
@JsonIgnoreProperties({"address"})
class Student {
private int id;
private String name;
private String address;
}
@JsonIgnore
on Specific Fields
If you want to ignore individual fields rather than all fields of a particular name, use @JsonIgnore
on the specific field.
This is field-specific and needs to be repeated for each field you want to ignore.
@Data
class University {
private int id;
private String name;
@JsonIgnore
private String address;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
This will ignore all null
properties at all levels of nesting. This can be placed on the root class or globally configured in ObjectMapper
.
This approach only ignores null values. It won’t work if the nested properties are non-null but you still want to exclude them.
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
class University {
private int id;
private String name;
private String address;
}
@JsonFilter
with SimpleBeanPropertyFilter
This is the most flexible but also more complex. It allows you to dynamically include or exclude properties using filters.
This allows you to dynamically configure which properties to include or exclude. It is powerful but requires more setup compared to other options.
@JsonFilter("universityFilter")
@Data
class University {
private int id;
private String name;
private String address;
}
@Data
@JsonFilter("studentFilter")
class Student {
private int id;
private String name;
private String address;
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
SimpleFilterProvider filters = new SimpleFilterProvider()
.addFilter("universityFilter", SimpleBeanPropertyFilter.serializeAllExcept("address"))
.addFilter("studentFilter", SimpleBeanPropertyFilter.serializeAllExcept("address"));
mapper.setFilterProvider(filters);
return mapper;
}
Recommendation:
- Use
@JsonIgnoreProperties
if the properties to be ignored are known at compile time. - Use
@JsonFilter
for dynamic scenarios where properties to be ignored can change at runtime.