Showing posts with label POJO. Show all posts
Showing posts with label POJO. Show all posts

Monday, September 5, 2011

Convert JSON String to Java Object (POJO)


 
 During the recent development came to a scenario where I want to convert the JSON string into the java object (POJO). to achieve this  i decided to use the "gson" API provided by the google. Following the is example how i have converted the JSON to POJO.

External API  : gson-1.3.jar from google.



import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonToPojo {

   /**
    * @param args
    */
public static void main(String[] args) {

String jsonString= "[{name:'Yogesh',address : 'Pimple Saudagar',age:29},
{name:'Puneet',address :'Hadapsar',age:27},                                               {name:'Sameer',address:'Wagholi',age:31}]";

Student [] students = getJsonFormString(jsonString, Student[].class);

for (Student student : students) {
System.out.println("Name  --> " + student.getName());
System.out.println("Address --> " + student.getAddress());
System.out.println("Age --> " + student.getAge());
}
}

/**
 * Returns the JSON representation from string.
 * 
 * @param <T>
 * @param json
 * @param type
 * 
 */
public static <T> T getJsonFormString(String json,  Class<T> type) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
return (T) gson.fromJson(json, type);
}

}

class Student {

private String name;
private String address;
private int age;

/**
 *  Constructor
 */
public Student (){

}

/**
 * @return the name
 */
public String getName() {
return name;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
this.name = name;
}

/**
 * @return the address
 */
public String getAddress() {
return address;
}

/**
 * @param address the address to set
 */
public void setAddress(String address) {
this.address = address;
}

/**
 * @return the age
 */
public int getAge() {
return age;
}

/**
 * @param age the age to set
 */
public void setAge(int age) {
this.age = age;
}
}