4/22/2011

Creating JSON String From Bean

I will use net.sf.json.* package for JSON processing. You can find the documentation and library files from here: http://json-lib.sourceforge.net/

Suppose you have the following class:
public class UserInfo {               

    String id;
    String userName;
    String birthPlace;

    // getters and setters here!

}
First, let's create an instance:
UserInfo userInfo = new UserInfo();
userInfo.setId("BFASHRGHFG");
userInfo.setUserName("User1");
userInfo.setBirthPlace("Madrid");
You can create JSON formatted string from this class with the following line:
String resultJson = JSONObject.fromObject(userInfo).toString();
resultJson will be:
{ "id" : "BFASHRGHFG", "userName" : "User1", "birthPlace" : "Madrid" }
We may want some fields not to be included in resulting json string, then we will create a JsonConfig instance and set exclude list of this instance:
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[] { "id" });
Then we may use this configuration as another parameter to fromObject method:
String resultJson = JSONObject.fromObject(userInfo,jsonConfig).toString();
resultJson will be:
{ "userName" : "User1", "birthPlace" : "Madrid" }

No comments:

Post a Comment