4/29/2011

Mapping JSON String to Bean

In this post, we will receive a json formatted string from a server or somewhere and try to map it directly to a matching java bean. For this reason, first, we have the following classes:
public class Account {

    String accountNo;
    String bankName;

    // getters and setters here!

}
public class UserInfo {

    String userID;
    String userName;
    String birthday;

    Account bankInfo;

    List<String> favoriteMovies;

    // getters and setters here!

}
Suppose you receive the following string from a server as response to some request:
{
    "accountNo" : "11833",
    "bankName" : "SopBank"
}
And you want to map this string a an already existing bean. First, we have to create a JSONObject from this string with the following line:
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(receivedJsonString);
Now we can map it to an account bean using JSONObject's toBean method:
Account newAccount = (Account) JSONObject.toBean(jsonObject,Account.class);
Now newAccount object will be:

Now we will map a class that has some other class types in it (other than primitives). Suppose you received the following json formatted string:
{
    "userID" : "HBSS234HSB",
    "userName" : "Cem Yilmaz",
    "birthday" : "01/01/1986",
    "bankInfo" : {
        "accountNo" : "11833",
        "bankName" : "SopBank"
    },
    "favoriteMovies" : [
        "Eternal Sunshine",
        "Fight Club",
        "Av Mevsimi"
    ]
}
Again we will create a JSONObject from this string:
JSONObject jsonObject2 = (JSONObject) JSONSerializer.toJSON(receivedJsonString);
This time we will introduce the non-primitive attributes of the UserInfo class to toBean method with a class map. This class map consists of attribute names and corresponding classes:
Map<String, Class> itemMap = new HashMap<String, Class>();
itemMap.put("bankInfo",Account.class);
Now we can create a UserInfo instance:
UserInfo userInfo = (UserInfo) JSONObject.toBean(jsonObject2,UserInfo.class,itemMap);
Now userInfo object will be:

Ref: http://json-lib.sourceforge.net/

No comments:

Post a Comment