
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Bean to JSON Object Excluding 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" }
Advertisements