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/

4/25/2011

Creating JSON String From Bean - 2

I have to say one more thing about JsonConfig class. Suppose you have a bean with not only primitive objects (like String, int etc.), but also some other classes.

Suppose your class structure is as follows. You have a Person class:
public class Person {

    String name;
    String surname;

    // getters and setters here!

}
And you have a family class that has some persons in it:
public class Family {

    Person mother;
    Person father;
    String anniversary;

    // getters and setters here!

}
Now let's create some instances:
Person person1 = new Person();
person1.setName("Münir");
person1.setSurname("Özkul");

Person person2 = new Person();
person2.setName("Adile");
person2.setSurname("Naşit");

Family family = new Family();
family.setFather(person1);
family.setMother(person2);
family.setAnniversary("01/01/1986");
Now we want JSON String of this family class. All we have to do is create a JsonConfig instance and set its classmap.
JsonConfig jsonConfig = new JsonConfig();

jsonConfig.setRootClass(Family.class);

Map<String,Class> itemMap = new HashMap<String,Class>();
itemMap.put("mother",Person.class);
itemMap.put("father",Person.class);

jsonConfig.setClassMap(itemMap);
In this classmap, we will add each non-primitive attribute of the root class (in this case Family) to the map with its corresponding classes. In this way, JSONObject will know how to call the getter and setter of this attribute.
Now we will again pass jsonConfig instance to fromObject method:
String resultJson = JSONObject.fromObject(family,jsonConfig).toString();
resultJson will be:
{
    "anniversary" : "01/01/1986",
    "mother" : {
            "name" : "Adile",
            "surname" : "Naşit"
    },
    "father" : {
            "name" : "Münir",
            "surname" : "Özkul"
    }
}

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

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" }

4/20/2011

Hoşgeldim

Hemen lafa girelim. Bu blogda ara sıra karaladıklarım, J2EE hakkında gerçekte uygulanmış çözümler ve paylaşmak istediğim yeni teknolojiler ve programlama örneklerini bulacaksınız. Çoğu, işyerimde kendimin denediği örnekler olacak. Ayrıca karşılaştığım sorunları, çözüm bulduğum siteleri ve teknolojileri de gönderiyor olacağım. Umarım devamlı bir blog olur.