JSONObject has overloaded constructor. You can call empty constructor or parameterized constructor. We can generate json format for any object using setters and getters method. By the way, we can eliminate the non public members from an object using the below syntax.


public JSONObject(java.lang.Object object,
                  java.lang.String[] names)

We can mention the public member in the String array to generate json . If a key(public member) is not found or not visible,which is mentioned in the String array , then it will not be copied into the new JSONObject.


import org.json.JSONObject;

public class JsonReflection {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Customer cust=new Customer();
		cust.setName("raja");
		cust.setAge(22);
		JSONObject json=new JSONObject(cust,new String[]{"name"});
		System.out.println(json.toString());
	}

}

output:

{"name":"raja"}

In the above program , we passed name only  in the String array. Here the name is marked as public member. That's why it display the json object or else the empty reslut will be returned. The customer bean class code


public class Customer {
public String name;
int age;
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
}