Spring Boot — Dynamically ignore fields while serializing Java Object to JSON
Lets consider we have a RestController class which has two endpoints to expose User & List<User>
Since id & dob fields in User object are sensitive, we don’t want to expose them in our endpoints.
Jackson library provides @JsonIgnore & @JsonIgnoreProperties annotations to ignore fields while serializing
Here is a sample code
One catch with @JsonIgnore & @JsonIgnoreProperties annotations are — They expect field names in compile time itself. But what if our consumer want to ignore few fields dynamically based on their input ?
We can use MappingJacksonValue class to achieve the above requirement
Here is the sample code
Remember the below points
- Properties which are to be ignored is supplied to SimpleBeanPropertyFilter.serializeAllExcept(“id”, “dob”). This can be easily made dynamic based on user input
- Filter name mentioned in SimpleFilterProvider() .addFilter(“userFilter”, simpleBeanPropertyFilter) has to match filer name provided in @JsonFilter(“userFilter”) annotation on User class
- We need to return MappingJacksonValue instance instead of User or List<User> (Refer line 19 & line 34)
Thats all folks !