
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Importance of JSONFilter Annotation in Java
The @JsonFilter annotation belongs to Jackson Annotations. Jackson Annotations are used during serialization and deserialization to denote a particular field (or method) that is declared in Java as an instance variable, is a JsonProperty, and should be ignored, or what condition should be applied to it. It is used to define a dynamic filter for serializing/deserializing Java objects.
@jsonfilter annotation
Let's discuss the importance of jsonfilter annotation as given below -
-
It is used to filter which fields or properties of an object should be included or excluded during serializing/deserializing.
-
It is used with FilterProvider or SimpleBeanPropertyFilter class(concrete class) to define a filter and then apply the filter by passing it to the objectMapper during serialization/deserialization.
-
FilterProvider class is an abstract class, and we use its concrete class, SimpleFilterProvider.
-
Instead of creating many separate classes to show different chunks of the same object, @JsonFilter permits to use of one class and hides specific fields during serializing/deserializing.
Example
In the program below, the @JsonFilter("customFilter") annotation is used on the FilterBean class. The customFilter ID is linked with SimpleFilterProvider, which allows the ObjectMapper to include only the empName field during JSON serialization, filtering out the other.
First, you need to create a class with @JsonFilter, then use FilterProvider in the Main code.
import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; public class JsonFilterAnnotationTest { public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); // Create a filter that allows only "empName" field FilterProvider filters = new SimpleFilterProvider() .addFilter("customFilter", SimpleBeanPropertyFilter.filterOutAllExcept("empName")); // filtering on ObjectMapper String jsonString = mapper.writer(filters).writeValueAsString(new FilterBean()); System.out.println(jsonString); // Output: {"empName":"Raja Ramesh"} } } @JsonFilter("customFilter") // match the filter name used in SimpleFilterProvider class FilterBean { public int empId = 110; public String empName = "Raja Ramesh"; public String gender = "male"; }
Output
{"empName":"Raja Ramesh"}