About Abhijeet Sutar

Abhijeet (ajduke) is self-taught, self-organized software developer. His current go to language is Java and also he is exploring other languages such as Scala, Ruby.

Getting Started with Google GSON

In Java world,  JSON is becoming de facto standard for data exchange format over XML because of its ease of use and efficiency in terms of transferring it.

If you don’t know about JSON, it is Javascript object notation, a text based data exchange format which is collection of name-value where name is strictly of string type and value can be int, boolean, array or another json object.

GSON is open source Java library developed by Google. It is an API for converting a Java object to/from json representation.

Why should you use it ?

  • Converts any Java object i.e new object or any existing/legacy object, to JSON and vice-versa.
  • Finest support for generic objects
  • Simple, convenient methods for conversions
  • No need of any annotation for fields for conversions
  • All the fields by default are included in conversions even private fields
  • If don’t want to include the field in conversion, use transient modifier for that field
  • It handles the null fields gracefully, by not including them in serialization output but during deserialization it is initialized back to null

How do you add it to project ?

Add it as dependency using one of following way

Using Maven

Add the following dependency to project’s pom.xml


Using Gradle

Add following to project’s build.gradle

repositories {
dependencies {
    compile 'com.google.code.gson:gson:2.2.4'

Use as unmanaged dependency

If you are not using any build tool, you can add gson jar to directly classpath or build path.

Download the latest jar from GSON project’s downloads page. The downloaded zip file contains 3 jar files – the binary, the source code and the javadoc. Grab the binary jar file and add it to your project classpath.

How to use it ?

For conversion of an object to/from json, you need to use the Gson class and its following 2 methods.

toJson()  => converts an object provided to json string, takes object to be converted as argument and returns the json representation string

fromJSon() => converts the json string to object, takes first param as json string as object and class literal of destination object and returns the destination object

You can use Gson instance/object multiple times as it does not maintain any state.

Following are few examples stating the use of GSON API.

Example 1 : For simple object

Consider the following model object for conversion purpose, but remember that you can convert any object


package in.ajduke.ap012;
* An model for gson demo 
* @author ajduke
public class ModelObject {
  String name;
  int val;
  boolean status;
  double f;
  public ModelObject(String name, int val, 
  boolean status, double f) {
    this.name = name;
    this.val = val;
    this.status = status;
    this.f = f;
  public String toString() {
    return "ModelObject [name=" + name + ",
    val=" + val + ", status="
    + status + ", f=" + f + "]";


Following is listing for conversion object to json representation,


final Gson gson = new Gson();
// original object instantiation
ModelObject modelObject = new ModelObject("myname", 12, true, 2.3);
System.out.println("toJson ---");
System.out.println("Original Java object : " + modelObject);
// converting an object to json object
String json = gson.toJson(modelObject);
System.out.println("Converted JSON string is : " + json);

// getting object from json representation
System.out.println("Original JSON string is : " + json);
// converting json to object
ModelObject modelObject1 = gson.fromJson(json, ModelObject.class);
System.out.println("Converted Java object : " + modelObject1);

Note the signature of fromJson() it takes second argument as the class literal of destination object.

Output as follows,


toJson ---
Original Java object : ModelObject [name=myname, val=12, status=true, f=2.3]
Converted JSON string is : {"name":"myname","val":12,"status":true,"f":2.3}
Original JSON string is : {"name":"myname","val":12,"status":true,"f":2.3}
Converted Java object : ModelObject [name=myname, val=12, status=true, f=2.3]

Example 2 : For generic objects

For converting back the generic object to java object from json representation, we need to use use extra object as shown in follows

Type collectionType =new TypeToken<{ generic-object-with-type-information }>(){}.getType();

You need to provide the destination class type to TypeToken type parameter information as shown above. This is to form the Type instance and this we need to pass it to fromJson() method as second argument.

Following listing shows example for conversion of generic classes or the classes from collections framework to/from json


package in.ajduke.ap012;
* An generified model for demo of gson conversion 
* @author ajduke
public class GenericModel<T> {
  T value;
  public GenericModel(T value) {
    this.value = value;
  public String toString() {
    return "Model2 [value=" + value + "]";


Gson gson = new Gson();

System.out.println("A generic object demo");
// a generified object
GenericModel<Integer> model = new GenericModel<>(12);

// converting to json representation
String json = gson.toJson(model);
System.out.println("json representation :" + json);

// converting back to object
Type collectionType = new TypeToken<GenericModel<Integer>>() {
GenericModel<Integer> modelObj = 
                  gson.fromJson(json, collectionType);
System.out.println("converted object representation: " + modelObj);

System.out.println("\nA object from collection framework\n");
// for collection framework objects
List<String> listOfString = new ArrayList<>();

// conversion to json
String jsonStr = gson.toJson(listOfString);
System.out.println("json representation :" + jsonStr);

Type collectionType2 = new TypeToken<List<String>>() {
List<String> listObj = gson.fromJson(jsonStr, collectionType2);
System.out.println("converted object representation: " + listObj);

Output as follows


A generic object demo
json representation :{"value":12}
converted object representation: Model2 [value=12]
A object from collection framework
json representation :["ajduke","ajduchess"]
converted object representation: [ajduke, ajduchess]

Example 3 : using transient

If you don’t want to include some field in json representation, you can use transient modifier to an variable declaration, then while converting it to json representation, GSON ignores that variable. But when converting back to an object from json string it initializes its default value depending on variable type.

Consider our ModelObject and lets skip the integer val from json representation so, modify the its declaration to transient as in following listing


package in.ajduke.ap012;
* An model for demo of gson conversion 
* @author ajduke
public class ModelObject {
  String name;
  transient int val;
  boolean status;
  double f;
  public ModelObject(String name, int val, 
   boolean status, double f) {
    this.name = name;
    this.val = val;
    this.status = status;
    this.f = f;
  public String toString() {
    return "ModelObject [name=" + name + ",
    val=" + val + ", status="
    + status + ", f=" + f + "]";

Following is listing


Gson gson = new Gson();
// original object
ModelObject modelObject = new ModelObject("namesake", 50, true, 4.3);
System.out.print("Original Java object : ");

// converting to an json representation
String json = gson.toJson(modelObject);
System.out.print("Converted JSON string is : ");

// getting back the object from json representation
ModelObject modelObject3 = gson.fromJson(json, ModelObject.class);
System.out.print("Converted Java object : ");

So, while converting it GSON ignores and output of above as follows


Original Java object : ModelObject [name=namesake, val=50, status=true, f=4.3]
Converted JSON string is : {"name":"namesake","status":true,"f":4.3}
Converted Java object : ModelObject [name=namesake, val=0, status=true, f=4.3]
Thats all folks, for GSON introduction !!

Note: I had given small code snippet for all examples, to access full length listing go to this gist on github

What’s next ?

In next some articles, i will show you some extra goodies of GSON library,

so, stay tuned !!!

Reference: Getting Started with Google GSON from our JCG partner Abhijeet Sutar at the ajduke’s blog blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

3 Responses to "Getting Started with Google GSON"

  1. Young says:

    in Github,I have forked fastjson which is json parse framework.(https://github.com/AlibabaTech/fastjson/wiki)

  2. Using gradle in Android Studio, you don’t need to manually update the build.gradle. After pasting a couple of jar files into my libs folder and then selecting “Add as Library” Droidio automatically updated me build.gradle file like so:

    dependencies {
    compile ‘com.android.support:appcompat-v7:+’
    compile fileTree(include: ['*.jar'], dir: ‘libs’)
    compile files(‘libs/commons-io-2.4.jar’)
    compile files(‘libs/gson-2.2.4.jar’)

    (I did not add the references to commons-io or gson directly, they were added for me automatically)

  3. Kanif says:

    Awesome tutorial..thanks

Leave a Reply

one + 8 =

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books