I know I am probably adding one more introduction to thousands of articles about GSON. I learned about GSON with my own experiment. I wrote this document for my colleagues so that they will have easy time learning one feature at a time. I am posting this to web so that everybody else can also benefit from it. If you like it, please let me know. If you don't like it, feel free to suggest improvements. Please note that this is not production ready code.
What is Gson?
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted at http://code.google.com/p/google-gson.
Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
Understanding Gson
Simple object representation in JSON and from JSON
Program
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
/**
*
* This simple class does two things, it serializes a java object Person into JSON representation and then deserializes the JSON string from file into * Person object.
* @author Shilpa Deshpande
*/
public class GsonTest {
private static final String FILE_LOCATION = "./file_" + System.currentTimeMillis() + ".json";
public static void main(String[] args) {
Person person = new Person("Jane", "Doe", 35);
Gson gson = new Gson();
String json = gson.toJson(person);
// Print JSON representation
System.out.println("JSON Representation: \n"+json);
// Write converted json data to a file named "file_somenumber.json"
File file = new File(FILE_LOCATION);
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.write(json);
writer.close();
}catch (IOException e) {
e.printStackTrace();
}
// Read file and then convert it into object
try {
BufferedReader br = new BufferedReader(new FileReader(FILE_LOCATION));
// convert the json string back to object
Person jperson = gson.fromJson(br, Person.class);
// Print object representation.
System.out.println("Object Representation: \n"+jperson);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (file.exists()) {
file.deleteOnExit();
}
}
}
public static class Person {
private String firstName;
private String lastName;
private int age;
/**
* We need to have no-arg constructor
*/
public Person() {
super();
}
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [First Name=" + firstName + ", Last Name=" + lastName + ", Age=" + age + "]\n");
return builder.toString();
}
}
}
Output:
The output will be
JSON Representation:
{"firstName":"Jane","lastName":"Doe","age":35}
Object Representation:
Person [First Name=Jane, Last Name=Doe, Age=35]
Observations:
One should have a no-arg constructor for the class which is being serialized.
One may or may not have getters and setters for the class.
Adding a list of objects to the Person.
Program
public static class Place {
private String cityName;
private State stateName; // Use enum
public Place() {
super();
}
public Place(String cityName, State stateName) {
this.cityName = cityName;
this.stateName = stateName;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Place [City=" + cityName + ", State=" + stateName + "]\n";
}
}
public static enum State {
AK, AL, AR, AZ, CA, CO, CT, DC, DE, FL, GA, HI, IA, ID, IL, IN, KS, KY, LA, MA, MD, ME, MI, MN, MO, MS, MT, NC, ND, NE, NH, NJ, NM, NV, NY, OH, OK, OR, PA, RI, SC, SD, TN, TX, UT, VA, VT, WA, WI, WV, WY
}
The test code will change in following manner
public static void main(String[] args) {
List placeList = new ArrayList();
Place place = new Place("Salt Lake City", State.UT);
placeList.add(place);
place = new Place("Lincoln", State.NE);
placeList.add(place);
Person person = new Person("Jane", "Doe", 35);
person.setPlaceList(placeList);
.............
}
Output
The output will be
JSON Representation:
{"firstName":"Jane","lastName":"Doe","age":35,"placeList":[{"cityName":"Salt Lake City","stateName":"UT"},{"cityName":"Lincoln","stateName":"NE"}]}
Object Representation:
Person [First Name=Jane, Last Name=Doe, Age=35]
Place [City=Salt Lake City, State=UT]
Place [City=Lincoln, State=NE]
Observations
- One can have embedded objects, as long as every object has no-arg constructor, deserialization works fine.
- One can use enum as a member of class.
Use of interfaces
When member of the object is a interface, it is important to let Gson know what impl is going to be used. Following changes in program are required to work with interfaces
Program
public static void main(String[] args) {
JobType job = new JobTypeImpl("Application Developer","Create software application");
List placeList = new ArrayList();
Place place = new Place("Salt Lake City", State.UT);
placeList.add(place);
place = new Place("Lincoln", State.NE);
placeList.add(place);
Person person = new Person("Jane", "Doe", 35);
person.setPlaceList(placeList);
person.setJobType(job);
# Create an implementation of InstanceCreator
class JobTypeInstanceCreator implements InstanceCreator {
@Override
public JobType createInstance(Type arg0) {
return new JobTypeImpl();
}
}
# Register JobType adapter with GsonBuilder and then create instance of Gson.
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(JobType.class, new JobTypeInstanceCreator());
Gson gson = builder.create();
public static interface JobType {
public String getDescrption();
public void setDescription(String description);
public String getTitle();
public void setTitle(String title);
}
public static class JobTypeImpl implements JobType {
private String title;
private String description;
public JobTypeImpl() {
super();
}
public JobTypeImpl(String title, String description) {
super();
this.title = title;
this.description = description;
}
@Override
public String getDescrption() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "JobTypeImpl [Title=" + title + ", Description=" + description + "]\n";
}
}
Output
JSON Representation:
{"firstName":"Jane","lastName":"Doe","age":35,"placeList":[{"cityName":"Salt Lake City","stateName":"UT"},{"cityName":"Lincoln","stateName":"NE"}],"job":{"title":"Application Developer","description":"Create software application"}}
Object Representation:
Person [First Name=Jane, Last Name=Doe, Age=35]
Place [City=Salt Lake City, State=UT]
Place [City=Lincoln, State=NE]
JobTypeImpl [Title=Application Developer, Description=Create software application]
Observations
One needs to use Implementation of InstanceCreator to specify exact implementation of the interface.
Use of third party classes
Let's assume Person class has another instance of org.joda.time.DateTime type. We do not have source code of this class, so we cannot modify it. Following piece of code shows how serialization and deserialization can work.
Program
class DateTimeSerializer implements JsonSerializer{ public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } } /* * Gson calls toJson() when it runs into a DateTime object during serialization. Writing a Deserializer Here is an example of how to write a custom deserializer for JodaTime DateTime class. */ class DateTimeDeserializer implements JsonDeserializer{ public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new DateTime(json.getAsJsonPrimitive().getAsString()); } } JobType job = new JobTypeImpl("Application Developer", "Create software application"); DateTime date = new DateTime(); ListplaceList = new ArrayList Place place = new Place("Salt Lake City", State.UT); placeList.add(place); place = new Place("Lincoln", State.NE); placeList.add(place); Person person = new Person("Jane", "Doe", 35); person.setPlaceList(placeList); person.setJobType(job); person.setDate(date); GsonBuilder builder = new GsonBuilder().registerTypeAdapter( JobType.class, new JobTypeInstanceCreator()); builder.registerTypeAdapter(DateTime.class, new DateTimeSerializer()); builder.registerTypeAdapter(DateTime.class, new DateTimeDeserializer()); Gson gson = builder.create();();
Output
JSON Representation:
{"firstName":"Jane","lastName":"Doe","age":35,"placeList":[{"cityName":"Salt Lake City","stateName":"UT"},{"cityName":"Lincoln","stateName":"NE"}],"job":{"title":"Application Developer","description":"Create software application"},"date":"2012-03-30T13:01:18.284-05:00"}
Object Representation:
Person [First Name=Jane, Last Name=Doe, Age=35]
Place [City=Salt Lake City, State=UT]
Place [City=Lincoln, State=NE]
JobTypeImpl [Title=Application Developer, Description=Create software application]
2012-03-30T13:01:18.284-05:00
Observations
One may need to use custom serializer, deserializer for third party classes.
Refer to the attached file for the complete program.
Ref:
Gson User Guide




