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/

No comments:

Post a Comment