Parsing JSON with Gson library

Ankit Sinhal
2 min readJan 16, 2017

In the previous article we understood the basics of JSON and popular libraries for JSON parsing. In this tutorial we are going to discuss about one of most important library, which most of you have used in your project development. This library is GSON developed by Google. This article will explain you some of the advance features provided by GSON which you can utilize.

For more sake of more details I divided the explanation in two parts. This is the Part 1 of the series.

GSON is open source and standalone library which is used to convert JSON data into java objects and vice versa. You can found it here.

Benefits of Gson?

· Convert any Java object to JSON and vice-versa.

· Support of generic objects.

· Allows to serialize a Collections of objects of the same type.

· Exclude the fields during conversion by using transient keyword or @Expose annotation.

· It handles the null fields, by not including them in serialization output but during de-serialization it is initialized back to null.

· Allow custom representations for objects.

· All the fields by default are included in conversions even private fields.

Using Gson

Gson is a primary class which you can just create by calling new Gson(). There is also a class GsonBuilder available that can be used to create a Gson instance with various settings like version control and so on.

To use with Maven

Add the following dependency in pom.xml with latest version:

<dependency>

<groupId>com.google.code.gson</groupId>

<artifactId>gson</artifactId>

<version>2.8.0</version>

</dependency>

To use with Gradle

Add the following dependency in build.gradle with latest version:

dependencies {

compile ‘com.google.code.gson:gson:2.8.0’

}

If you are not using any build system, then you can download the latest jar file from here and add gson jar in classpath or build path.

Getting Started

Create a new Android project

Here is sample nested JSON which is reading from Android assets folder.

Employee.java

You will notice that fields in the Employee.java have the @SerializedName(“”) annotation. This is used when the property name in the java class does not match the field name in JSON.

In order to do the serialization, we need a Gson object, which handles the conversion and then our JSON to a Java object with fromJson():

Here we converted JSON into our Employee object and displayed values.

The sample code is available at GitHub.

Stay tuned for the Part 2 of this series soon for more advance details on GSON library.

Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful.

Check out my blogger page for more interesting topics on Software development at http://androidjavapoint.blogspot.in

You can also find my Android Applications on play store

--

--

Ankit Sinhal

Senior Software Engineer at Walmart. Dreamer and Achiever..