#The JsonConfig class is a utility class that helps configure the serialization process. We can use the setExcludes() method of the JsonConfig class to convert a bean into a JSON object and exclude some of its properties, and pass this JSON configuration instance to the parameter of the static method fromObject() of JSONObject.
public void setExcludes(String[] excludes)
In the below example, we can convert bean to a JSON object by excluding some of the properties.
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 The age and address attributes can be excluded from the output.
{ "firstName": "Raja", "lastName": "Ramesh" }
The above is the detailed content of How to use JsonConfig in Java to convert bean to JSON object and exclude certain properties?. For more information, please follow other related articles on the PHP Chinese website!