Sunday, November 6, 2011

Using GSON Effectively

Program of Deserialize/Serialize JSON.I am writing it below. First download the Gson then add it to the eclipse project.

Step 1: Create a Dog class with getters and setters as below.
package myobject;
public class Dog {
String name;
int age
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Step 2: Write a common GsonSerializer as below with generics so any class type can be passed.

package common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
//Generics is used so any class type can be passed
public class GsonSerializer<T> {
public T Deserialize(String json, Class classOfT) {
Gson gn = new GsonBuilder().create();
return (T) gn.fromJson(json, classOfT);
}
public String Serialize(T object) {
Gson gn = new GsonBuilder().create();
return gn.toJson(object);
}
}
 3: Write a main method for calling the example
package gsoncaller;
import myobject.Dog;
import common.GsonSerializer;
public class MyGsonCaller {
public static void main(String[] args) {
Dog dog = new Dog();
dog.setAge(1);
dog.setName("mela");
GsonSerializer<Dog> serializer = new GsonSerializer<Dog>();
serializer.Serialize(dog);
System.out.println("My json string ::>" + serializer.Serialize(dog));
dog = serializer.Deserialize(serializer.Serialize(dog), Dog.class);
String name = dog.getName();
int age = dog.getAge();
System.out.println("Name ::>" + name);
System.out.println("Age ::>" + age);
}
}
The out put is:

My json string ::>{"name":"mela","age":1}
Name ::>mela
Age ::>1





2 comments:

  1. Hi, i come here through "stackoverflow". you answered my question before.
    and you linked you blog in answer. i read this article.
    i want to know about Gson.
    i am using google app engine and also datastore.
    i have to make information in datasotre to json.
    is it possible to make information convert to json easy using Gson?

    ReplyDelete
  2. GSON is given by google to convert Java Objects to JSON, Its the best way to do it.

    You can find much more detail with this site, all most every project is using the Gson.

    https://code.google.com/p/google-gson/

    ReplyDelete