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

What is the importance of @JsonFilter annotation in Java?

WBOY
Release: 2023-09-12 16:25:02
forward
1109 people have browsed it

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
Copy after login

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";
}
Copy after login

Output

{"empName":"Raja Ramesh"}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template