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 an 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
 1apply plugin: 'java'
 2apply plugin: 'idea'
 3apply plugin: 'application'
 4
 5mainClassName = 'com.firstfewlines.ParseJsonSample'
 6
 7repositories {
 8    mavenCentral()
 9}
10
11dependencies {
12    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
13}

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
 1package com.firstfewlines;
 2
 3public class Address {
 4    private String addressLine;
 5    private int zipCode;
 6
 7    public void setAddressLine(String addressLine) {
 8        this.addressLine = addressLine;
 9    }
10
11    public void setZipCode(int zipCode) {
12        this.zipCode = zipCode;
13    }
14
15    @Override
16    public String toString() {
17        return "Address{" +
18                "addressLine='" + addressLine + '\'' +
19                ", zipCode=" + zipCode +
20                '}';
21    }
22}

Employee.java
 1package com.firstfewlines;
 2
 3import java.util.Date;
 4import java.util.List;
 5
 6public class Employee {
 7    private String name;
 8    private Date doj;
 9    private double salary;
10    private boolean married;
11    private int experience;
12
13    List<Address> addressList;
14
15    public void setName(String name) {
16        this.name = name;
17    }
18
19    public void setDoj(Date doj) {
20        this.doj = doj;
21    }
22
23    public void setSalary(double salary) {
24        this.salary = salary;
25    }
26
27    public void setMarried(boolean married) {
28        this.married = married;
29    }
30
31    public void setExperience(int experience) {
32        this.experience = experience;
33    }
34
35    public void setAddressList(List<Address> addressList) {
36        this.addressList = addressList;
37    }
38
39    @Override
40    public String toString() {
41        return "Employee{" +
42                "name='" + name + '\'' +
43                ", doj=" + doj +
44                ", salary=" + salary +
45                ", married=" + married +
46                ", experience=" + experience +
47                ", \naddressList=" + addressList +
48                '}';
49    }
50}

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
 1package com.firstfewlines;
 2
 3import com.google.gson.Gson;
 4import com.google.gson.reflect.TypeToken;
 5
 6import java.lang.reflect.Type;
 7import java.text.SimpleDateFormat;
 8import java.util.ArrayList;
 9import java.util.List;
10
11public class ParseJsonSample {
12    public static void main(String [] argv) throws Exception {
13
14        Gson gson = new Gson();
15                //We can also use new GsonBuilder().create();
16
17        Employee employee = new Employee();
18        employee.setName("Vikash Verma");
19        employee.setSalary(55000.50);
20        employee.setDoj(new SimpleDateFormat("MM/dd/yyyy").parse("04/23/2017"));
21        employee.setMarried(true);
22        employee.setExperience(4);
23
24        Address addr1 = new Address();
25        addr1.setAddressLine("Kolkata");
26        addr1.setZipCode(700063);
27
28        Address addr2 = new Address();
29        addr2.setAddressLine("Mumbai");
30        addr2.setZipCode(400008);
31
32        List<Address> addressList = new ArrayList<>();
33
34        addressList.add(addr1);
35        addressList.add(addr2);
36        employee.addressList = addressList;
37
38        String jsonEmployee = gson.toJson(employee, employee.getClass());
39        System.out.println("\nEmployee to JSON: \n" + jsonEmployee);
40
41        Employee employee2 = gson.fromJson(jsonEmployee, Employee.class);
42        System.out.println("\nJSON to Employee: \n" + employee2.toString());
43
44        String jsonAddressList = gson.toJson(addressList, addressList.getClass());
45        System.out.println("\nAddress list to JSON: \n" + jsonAddressList);
46
47        Type listType = new TypeToken<List<Address>>() {}.getType();
48        List<Address> addressList2 = gson.fromJson(jsonAddressList, listType);
49        System.out.println("\nJSON to Address list: \n" + addressList2.toString());
50
51    }
52}
53

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

 1Employee to JSON:
 2{"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
 38}]}
 4
 5JSON to Employee:
 6Employee{name='Vikash Verma', doj=Sun Apr 23 00:00:00 IST 2017, salary=55000.5, married=true, experience=4,
 7addressList=[Address{addressLine='Kolkata', zipCode=700063}, Address{addressLine='Mumbai', zipCode=400008}]}
 8
 9Address list to JSON:
10[{"addressLine":"Kolkata","zipCode":700063},{"addressLine":"Mumbai","zipCode":400008}]
11
12JSON to Address list:
13[Address{addressLine='Kolkata', zipCode=700063}, Address{addressLine='Mumbai', zipCode=400008}]
14

References:


Download source code:


comments powered by Disqus