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

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

Following is listing for conversion object to json representation,

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

Output as follows,

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

Output as follows

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

Following is listing

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

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 !!!

About these ads

5 thoughts on “Getting Started with Google GSON

  1. Thank you very much for the great article. this is very useful post. All the points you mentioned are relevant and put together in an interesting way. keep it up.

  2. Great article. I’m glad I came across it just as I started using Gson. I haven’t needed to exclude a field yet, but now I know how! Thanks!

    Just a couple of suggestions, if I may:
    1. I would add “serialize” and “deserialize” to the “toJson” and “fromJson” definitions.
    2. Add a non-primitive private member to ModelObject (like ModelObjectComponent) to show off how Gson will recursively serialize your objects. This is what’s really awesome about Gson. However, his may just clutter what is otherwise a quick and clean intro to Gson.

  3. Pingback: Using Google GSON : Extra Goodies : Part I | ajduke's blog

  4. Pingback: Using Google GSON : Extra Goodies : Part II | ajduke's blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s