Importance of @JsonFilter annotation in Java?

JavaJSONObject Oriented ProgrammingProgramming

The @JsonFilter annotation used to define a custom filter to serialize the Java objects. We need to use the FilterProvider class to define a filter and get the actual filter instance. Now the filter configured by assigning the FilterProvider to ObjectMapper class.


public @interface JsonFilter

In the below example, the customFilter can be declared as an argument to @JsonFilter annotation extracts only the name and filtering out the other properties of a bean.


import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
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();
      FilterProvider filterProvider = new SimpleFilterProvider().addFilter("customFilter",   SimpleBeanPropertyFilter.filterOutAllExcept("empName"));
      String jsonString = mapper.writer(filterProvider).writeValueAsString(new FilterBean());
class FilterBean {
   public int empId = 110;
   public String empName = "Raja Ramesh";
   public String gender = "male";


{"empName":"Raja Ramesh"}
Published on 07-Nov-2019 09:28:48