Parse json string using Google Gson

Google Gson is very popular library to convert JSON to object and vice versa. The formJson(…) and toJson(…) are the two main APIs for the same. In this example we will see how to perform following JSON parsing operations using those APIs.

1. Convert a object to JSON string
2. Convert a list of objects to JSON string
3. Parse JSON string to convert to object
4. Parse JSON string to convert to List of objects

Like the other examples, I am using gradle as build system. In build.gradle we have to include the Google Gson library as dependency.

build.gradle
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'application'

mainClassName = 'com.firstfewlines.ParseJsonSample'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
}


In this example we will use two data classes for performing the json conversion: Address and Employee. The Employee class contains a list of addresses along with other various simple data types.

Address.java
package com.firstfewlines;

public class Address {
    private String addressLine;
    private int zipCode;

    public void setAddressLine(String addressLine) {
        this.addressLine = addressLine;
    }

    public void setZipCode(int zipCode) {
        this.zipCode = zipCode;
    }

    @Override
    public String toString() {
        return "Address{" +
                "addressLine='" + addressLine + '\'' +
                ", zipCode=" + zipCode +
                '}';
    }
}


Employee.java
package com.firstfewlines;

import java.util.Date;
import java.util.List;

public class Employee {
    private String name;
    private Date doj;
    private double salary;
    private boolean married;
    private int experience;

    List<Address> addressList;

    public void setName(String name) {
        this.name = name;
    }

    public void setDoj(Date doj) {
        this.doj = doj;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public void setMarried(boolean married) {
        this.married = married;
    }

    public void setExperience(int experience) {
        this.experience = experience;
    }

    public void setAddressList(List<Address> addressList) {
        this.addressList = addressList;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", doj=" + doj +
                ", salary=" + salary +
                ", married=" + married +
                ", experience=" + experience +
                ", \naddressList=" + addressList +
                '}';
    }
}


And finally the main class is here. We are first converting the object to JSON string and then parsing back the same JSON into object. Notice that Employee is a complex object containing list of Address objects. That being converted to and from JSON string very easily. Even the list of Address is converted to JSON string easily.

When we want to parse JSON of array of Address into a list of Address’es, we have to create a TypeToken instance to determine the type and specify that while parsing.

ParseJsonSample.java
package com.firstfewlines;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class ParseJsonSample {
    public static void main(String [] argv) throws Exception {

        Gson gson = new Gson();
                //We can also use new GsonBuilder().create();

        Employee employee = new Employee();
        employee.setName("Vikash Verma");
        employee.setSalary(55000.50);
        employee.setDoj(new SimpleDateFormat("MM/dd/yyyy").parse("04/23/2017"));
        employee.setMarried(true);
        employee.setExperience(4);

        Address addr1 = new Address();
        addr1.setAddressLine("Kolkata");
        addr1.setZipCode(700063);

        Address addr2 = new Address();
        addr2.setAddressLine("Mumbai");
        addr2.setZipCode(400008);

        List<Address> addressList = new ArrayList<>();

        addressList.add(addr1);
        addressList.add(addr2);
        employee.addressList = addressList;

        String jsonEmployee = gson.toJson(employee, employee.getClass());
        System.out.println("\nEmployee to JSON: \n" + jsonEmployee);

        Employee employee2 = gson.fromJson(jsonEmployee, Employee.class);
        System.out.println("\nJSON to Employee: \n" + employee2.toString());

        String jsonAddressList = gson.toJson(addressList, addressList.getClass());
        System.out.println("\nAddress list to JSON: \n" + jsonAddressList);

        Type listType = new TypeToken<List<Address>>() {}.getType();
        List<Address> addressList2 = gson.fromJson(jsonAddressList, listType);
        System.out.println("\nJSON to Address list: \n" + addressList2.toString());

    }
}


How to run:

  • Make sure you have latest version of Gradle installed and PATH is configured.
  • Download the sample and unzip it
  • Go to the directory where you unzipped the file i.e. where the build.gradle is there
  • Run gradle run command

Alternatively, you can use IntelliJ IDEa or Eclipse to import the Gradle project and run from there.

This should run the application with output similar to below

Employee to JSON:
{"name":"Vikash Verma","doj":"Apr 23, 2017 12:00:00 AM","salary":55000.5,"married":true,"experience":4,"addressList":[{"addressLine":"Kolkata","zipCode":700063},{"addressLine":"Mumbai","zipCode":40000
8}]}

JSON to Employee:
Employee{name='Vikash Verma', doj=Sun Apr 23 00:00:00 IST 2017, salary=55000.5, married=true, experience=4,
addressList=[Address{addressLine='Kolkata', zipCode=700063}, Address{addressLine='Mumbai', zipCode=400008}]}

Address list to JSON:
[{"addressLine":"Kolkata","zipCode":700063},{"addressLine":"Mumbai","zipCode":400008}]

JSON to Address list:
[Address{addressLine='Kolkata', zipCode=700063}, Address{addressLine='Mumbai', zipCode=400008}]


References:


Download source code:


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus