How to convert a bean to JSON object using Exclude Filter in Java?


The JsonConfig class can be used to configure the serialization process. We can use the setJsonPropertyFilter() method of JsonConfig to set the property filter when serializing to JSON. We need to implement a custom PropertyFilter class by overriding the apply() method of the PropertyFilter interface. It returns true if the property will be filtered out or false otherwise.

Syntax

public void setJsonPropertyFilter(PropertyFilter jsonPropertyFilter)

Example

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
public class ConvertBeanToJsonExcludeFilterTest {
   public static void main(String[] args) {
      Student student = new Student("Sai", "Chaitanya", 20, "Hyderabad");
      JsonConfig jsonConfig = new JsonConfig();
      jsonConfig.setJsonPropertyFilter(new CustomPropertyFilter());

      JSONObject jsonObj = JSONObject.fromObject(student, jsonConfig);
      System.out.println(jsonObj.toString(3)); //pretty print JSON
   }
   public static class Student {
      private String firstName, lastName, address;
      public int age;
      public Student(String firstName, String lastName, int age, String address) {
         super();
         this.firstName = firstName;
         this.lastName = lastName;
         this.age = age;
         this.address = address;
      }
      public String getFirstName() {
         return firstName;
      }
      public String getLastName() {
         return lastName;
      }
      public int getAge() {
         return age;
      }
      public String getAddress() {
         return address;
      }
   }
}
// CustomPropertyFilter class
class CustomPropertyFilter implements PropertyFilter {
   @Override
   public boolean apply(Object source, String name, Object value) {
      if(Number.class.isAssignableFrom(value.getClass()) ||        String.class.isAssignableFrom(value.getClass())) {
         return false;
      }
      return true;
   }
}

Output

{
  "firstName": "Sai",
  "lastName": "Chaitanya",
  "address": "Hyderabad",
  "age": 20
}

Updated on: 08-Jul-2020

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements