Importance of @JsonFilter annotation in Java?


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.

Syntax

@Target(value={ANNOTATION_TYPE,TYPE,METHOD,FIELD,PARAMETER})
@Retention(value=RUNTIME)
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.

Example

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());
      System.out.println(jsonString);
   }
}

@JsonFilter("customFilter")
class FilterBean {
   public int empId = 110;
   public String empName = "Raja Ramesh";
   public String gender = "male";
}

Output

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