How to convert bean to JSON object by excluding some properties using JsonConfig in Java?


The JsonConfig class is a utility class that helps to configure the serialization process. We can convert a bean to a JSON object with few properties that can be excluded using the setExcludes() method of JsonConfig class and pass this JSON config instance to an argument of static method fromObject() of JSONObject.

Syntax

public void setExcludes(String[] excludes)

In the below example, we can convert bean to a JSON object by excluding some of the properties.

Example

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class BeanToJsonExcludeTest {
   public static void main(String[] args) {
      Student student = new Student("Raja", "Ramesh", 35, "Madhapur");
      JsonConfig jsonConfig = new JsonConfig();
      jsonConfig.setExcludes(new String[]{"age", "address"});
      JSONObject obj = JSONObject.fromObject(student, jsonConfig);
      System.out.println(obj.toString(3)); //pretty print JSON
   }
   public static class Student {
      private String firstName, lastName, address;
      private 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;
      }
   }
}

In the below output, age and address properties can be excluded.

Output

{
   "firstName": "Raja",
   "lastName": "Ramesh"
}

Updated on: 08-Jul-2020

813 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements