Parsing JSON with Gson library

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?
1. Convert any Java object to JSON and vice-versa.
2. Allows to serialize a Collections of objects of the same type.
3. Exclude the fields during conversion by using transient keyword or @Expose annotation.
4. It handles the null fields, by not including them in serialization output but during de-serialization it is initialized back to null.
5. Allow custom representations for objects.
6. All the fields by default are included in conversions even private fields.
7. Support of generic objects.
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 and add 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.


SampleJson

{
  "Id": 11111,
  "PersonalDetails": {
    "name": "Employee1",
    "age": 30,
    "bloodGroup": "B+",
    "address": "address"
  }
}


Employee.java

package com.androidjavapoint.gsonsample;

import com.google.gson.annotations.SerializedName;

import java.util.Date;

public class Employee {
    @SerializedName("Id")
    public long id;

    @SerializedName("PersonalDetails")
    public PersonalDetails personalDetails;
}



PersonalDetails.java

package com.androidjavapoint.gsonsample;

import com.google.gson.annotations.SerializedName;

public class PersonalDetails {
    public String name;

    public int age;

    public String bloodGroup;
}


GsonParsing

Gson gson = new Gson();
Employee employee = gson.fromJson(mJsonString, Employee.class);
PersonalDetails personalDetails = employee.personalDetails;

StringBuilder resultBuilder = new StringBuilder();
resultBuilder.append("Employee Details:");
resultBuilder.append("\n");
esultBuilder.append("Id: " + employee.id);
resultBuilder.append("\n");
resultBuilder.append("Name: " + personalDetails.name);
resultBuilder.append("\n");
resultBuilder.append("Age: " + personalDetails.age);
resultBuilder.append("\n");
resultBuilder.append("blood Group: " + personalDetails.bloodGroup);


In the GsonParsing we’ve created an instance of Gson and converted JSON into our Employee object and displayed values.

The sample code is available at GitHub in which I am reading the JSON from Android assets folder and parsing it using GSON.

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

To find more interesting topics on Software development follow me at https://medium.com/@ankit.sinhal

You can also find my Android Applications on play store

Comments

Popular posts from this blog

Android O: Impact On Running Apps And Developer Viewpoint

Android Performance: Avoid using ENUM on Android

Local Broadcast, less overhead and secure in Android