Home  >  Article  >  Java  >  What is the importance of @JsonFilter annotation in Java?

What is the importance of @JsonFilter annotation in Java?

WBOY
WBOYforward
2023-09-12 16:25:021020browse

What is the importance of @JsonFilter annotation in Java?

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

Syntax

@Target(value={ANNOTATION_TYPE,TYPE,METHOD,FIELD,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonFilter

In the example below, customFilter can be declared as a parameter of the @JsonFilter annotation, which only extracts the name and filters Drop the other attribute beans of a.

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")<strong>
</strong>class FilterBean {
   public int empId = 110;
   public String empName = "Raja Ramesh";
   public String gender = "male";
}

Output

{"empName":"Raja Ramesh"}

The above is the detailed content of What is the importance of @JsonFilter annotation in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete