Jackson @JsonFilter Example

By Arvind Rai, June 14, 2018
On this page we will provide Jackson @JsonFilter annotation example. @JsonFilter defines a filter name using which we filter out properties in JSON serialization. @JsonFilter are used at class level. It can also be used at property level since Jackson 2.3. Jackson provides SimpleFilterProvider that is used to add filters to ObjectMapper. To create the instance of SimpleFilterProvider we need to pass filter name and the instance of SimpleBeanPropertyFilter. The instance of SimpleBeanPropertyFilter are created by its methods such as serializeAllExcept() and filterOutAllExcept() methods. Now find the complete example of @JsonFilter step by step.

Technologies Used

Find the technologies being used in our example.
1. Java 9
2. Jackson 2.9.5
3. Gradle 4.3.1

Gradle File

Find the Gradle file used in our example. build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'concretepage'
version = '0.0.1-SNAPSHOT' 
repositories {
    mavenCentral()
}
dependencies {
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.5'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.5'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.5'
} 

Using @JsonFilter

Find the steps to use @JsonFilter annotation.
Step-1: Create a class annotated with @JsonFilter and assign a filter name.
Student.java
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonFilter("studentFilter")
public class Student {
	@JsonProperty("stdName")
	private String name;

	@JsonProperty("stdAge")	
	private Integer age;

	@JsonProperty("stdCollege")	
	private String college;
	
	@JsonProperty("stdCity")	
	private String city;
	
	public Student() {}
	public Student(String name, Integer age, String college, String city) {
		this.name = name;
		this.age = age;
		this.college = college;
		this.city = city;
	}	
} 
In the above class we have created a filter named as studentFilter.
Step-2: Create the instance of SimpleFilterProvider and add our filter studentFilter using addFilter() method.
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("studentFilter",
        SimpleBeanPropertyFilter.serializeAllExcept("stdName", "stdCity")); 
We can use serializeAllExcept() and filterOutAllExcept() from SimpleBeanPropertyFilter to filter the properties.
Step-3: Set the instance of SimpleFilterProvider to ObjectMapper using setFilterProvider() method.
ObjectMapper mapper = new ObjectMapper();
mapper.setFilterProvider(filterProvider); 
Step-4: Now serialize the instance of Student class.
Student student = new Student("Mohit", 30, "ABCD", "Varanasi");   
String jsonData = mapper.writerWithDefaultPrettyPrinter()
       .writeValueAsString(student);
System.out.println(jsonData); 
stdName and stdCity properties will not be serialized. Find the output.
{
  "stdAge" : 30,
  "stdCollege" : "ABCD"
} 

SimpleBeanPropertyFilter

SimpleFilterProvider is the implementation of PropertyFilter that only uses property name to determine if it should be serialized or filtered out. Find some methods of SimpleFilterProvider.
serializeAllExcept(): Serializes all properties except the properties configured to this method.
filterOutAllExcept(): Serializes properties only configured to this method.
serializeAll(): Serializes all properties and filters out nothing.

1. Using serializeAllExcept(): Find the sample code to use serializeAllExcept() method.
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("studentFilter",
       SimpleBeanPropertyFilter.serializeAllExcept("stdName", "stdCity")); 
serializeAllExcept() serializes all properties except the properties configured to this method. In the JSON output, the stdName and stdCity properties will not be serialized. Find the output.
{
  "stdAge" : 30,
  "stdCollege" : "ABCD"
} 
We can also use Java Set with serializeAllExcept() method.
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
Set<String> props = new HashSet<>();
props.add("stdName");
props.add("stdCity");
filterProvider.addFilter("studentFilter",
         SimpleBeanPropertyFilter.serializeAllExcept(props)); 
2. Using filterOutAllExcept(): Find the sample code to use filterOutAllExcept() method.
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("studentFilter",
      SimpleBeanPropertyFilter.filterOutAllExcept("stdName", "stdCity")); 
filterOutAllExcept() serializes properties only configured to this method and filters other properties. In the JSON output, only stdName and stdCity properties will be serialized. Find the output.
{
  "stdName" : "Mohit",
  "stdCity" : "Varanasi"
} 
We can also use Java Set with filterOutAllExcept() method.
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
Set<String> props = new HashSet<>();
props.add("stdName");
props.add("stdCity");
filterProvider.addFilter("studentFilter",
       SimpleBeanPropertyFilter.filterOutAllExcept(props)); 

@JsonFilter at Property Level

We can use @JsonFilter annotation on fields, methods and constructor parameters since Jackson 2.3. Here we will create two filters using @JsonFilter at property level and filter the properties using serializeAllExcept() and filterOutAllExcept() methods. Find the example.
Company.java
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Company {
	@JsonProperty("compName")		
        private String name;
	
	@JsonFilter("ceoFilter")
	@JsonProperty("compCeo")		
        private Employee ceo;

	@JsonFilter("addressFilter")	
	@JsonProperty("compAddress")		
        private Address address;
	
	public Company() {}
	public Company(String name, Employee ceo, Address address) {
		this.name = name;
		this.ceo = ceo;
		this.address = address;
	}
} 
Employee.java
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Employee {
	@JsonProperty("empName")
	private String name;

	@JsonProperty("empAge")	
	private Integer age;

	@JsonProperty("empProfile")	
	private String profile;

	public Employee() {}
	public Employee(String name, Integer age, String profile) {
		this.name = name;
		this.age = age;
		this.profile = profile;
	}	
} 
Address.java
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Address {
	@JsonProperty("city")	
        private String city;
	
	@JsonProperty("state")
        private String state;
	
	@JsonProperty("country")
        private String country;
	
	public Address() {}
	public Address(String city, String state, String country) {
		this.city = city;
		this.state = state;
		this.country = country;
	}
} 
CompanyToJSON.java
package com.concretepage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

public class CompanyToJSON {
  public static void main(String[] args) throws JsonProcessingException {
     SimpleFilterProvider filterProvider = new SimpleFilterProvider();
     filterProvider.addFilter("ceoFilter",
             SimpleBeanPropertyFilter.serializeAllExcept("empProfile"));
     
     filterProvider.addFilter("addressFilter",
             SimpleBeanPropertyFilter.filterOutAllExcept("state", "country"));
     
     ObjectMapper mapper = new ObjectMapper();
     mapper.setFilterProvider(filterProvider);
     
     Employee emp = new Employee("Krishna", 45, "Manager");
     Address address = new Address("Noida", "UP", "India");
     Company company = new Company("XYZ", emp, address);
     String jsonData = mapper.writerWithDefaultPrettyPrinter()
		 .writeValueAsString(company);
     System.out.println(jsonData);
  }
} 
Output
{
  "compName" : "XYZ",
  "compCeo" : {
    "empName" : "Krishna",
    "empAge" : 45
  },
  "compAddress" : {
    "state" : "UP",
    "country" : "India"
  }
} 

Reference

Annotation Type JsonFilter

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us