How to convert JSON to Object and Object to JSON using Google Gson

In previous post we learned How to parse/encode-decode JSON using JSON.simple.JSON is known for its light weight data exchange format. In web centric application integrated with Object oriented infrastructure, their will be high volume of data exchange and data are sent in form of JSON over wires.So, how do we convert (serialize) object to JSON and retrieve that object to JSON(deserialize). The main agenda of this post is understand serialization and de-serialization using GSON- an open source java library for converting Java Objects into their JSON and from JSON to java Objects. Some important features of GSON:
  • Gson has extensive support for java generics.Gson can be used to convert complex hierarchy of connected object model into JSON and vice versa.
  • Gson can work with arbitrary Java objects including pre-existing objects whose source code we cannot modify.Gson can also be used to convert third party object into JSON.
Remember, sample code speaks louder than raw text. Lets setup development environment, first download the required jar or configure maven dependency.
1. Gson jar can be downloaded from here
2. Maven dependency : Add following dependency in pom.xml
   <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>1.7.1</version>
   </dependency>

Java Object to JSON using Gson

 Create a java project and add download jar in class path/add dependency in pom.xml, if maven project. Create a POJO Employee.java, we will create employee list and convert it into JSON. Create a Employee.java  with following code lines: Here we have two level of class hierarchy - connected object model (SalaryComponents inside Employee).
Hide code lines
package com.devinline.model;

/**
 
 @author nikhil
 */
public class Employee {
  private String employeeName;
  private String employeeId;
  private String designation;
  private SalaryComponents salaryComponent;
  private String takeHomeSalary;

  public String getTakeHomeSalary() {
    return takeHomeSalary;
  }

  public void setTakeHomeSalary(String takeHomeSalary) {
    this.takeHomeSalary = takeHomeSalary;
  }

  public Employee() {

  }

  public Employee(String employeeName, String employeeId, 
      String designation,
      SalaryComponents salaryComponent) {
    super();
    this.employeeName = employeeName;
    this.employeeId = employeeId;
    this.designation = designation;
    this.salaryComponent = salaryComponent;
  }

  public void setsalaryComponent(SalaryComponents 
      salaryComponent) {
    this.salaryComponent = salaryComponent;
  }

  public String getEmployeeName() {
    return employeeName;
  }

  public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
  }

  public String getEmployeeId() {
    return employeeId;
  }

  public void setEmployeeId(String employeeId) {
    this.employeeId = employeeId;
  }

  public String getDesignation() {
    return designation;
  }

  public void setDesignation(String designation) {
    this.designation = designation;
  }

  public SalaryComponents getsalaryComponent() {
    return salaryComponent;
  }

  public static class SalaryComponents {
    private int basicSalary;
    private int hra;
    private int pfDeduction;
    private int spclAllowance;

    public SalaryComponents(int basicSalary, int hra, 
        int pfDeduction,
        int spclAllowance) {
      super();
      this.basicSalary = basicSalary;
      this.hra = hra;
      this.pfDeduction = pfDeduction;
      this.spclAllowance = spclAllowance;
    }

    public int getBasicSalary() {
      return basicSalary;
    }

    public void setBasicSalary(int basicSalary) {
      this.basicSalary = basicSalary;
    }

    public int getHra() {
      return hra;
    }

    public void setHra(int hra) {
      this.hra = hra;
    }

    public int getPfDeduction() {
      return pfDeduction;
    }

    public void setPfDeduction(int pfDeduction) {
      this.pfDeduction = pfDeduction;
    }

    public int getSpclAllowance() {
      return spclAllowance;
    }

    public void setSpclAllowance(int spclAllowance) {
      this.spclAllowance = spclAllowance;
    }

  }
}
Now we will create our processing unit ,SerialDeserialUsinGson.java with following code lines. Here we have created Gson object (using default constructor with default values).We can create Gson object with various customization like changing fields name, allow serialization of nulls by passing boolean value(by default nulls are serialized). We will revisit this advanced concept later. As of now use default values of Gson class.
Hide code lines
package com.sample.json;

import java.util.LinkedList;

import com.devinline.model.Employee;
import com.devinline.model.Employee.SalaryComponents;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SerialDeserialUsinGson {

 public static void main(String[] args) {
  LinkedList<Employee> empList = new LinkedList<>();
  // Create two Employee object and add to empList
  for (int i = 0; i < 2; i++) {
    empList.add(new Employee("Nikhil" + i, "007" 1
      "SE" + i,
          new SalaryComponents(1000 * i, 800 * i,
         300 * i,
           200 * i)));
  }
  // Create Gson Object using default values
  Gson gsonObj = new Gson();
  String employeesJSON = gsonObj.toJson(empList);
  System.out.println(employeesJSON);// display compact JSON
  /*System.out.println(new GsonBuilder().setPrettyPrinting().
      create().toJson(empList));*/
 }

}
Let's walk thorough the above code, first we created two employee object via for loop(Scary code☺) just ignore the logic.Next we created Gson object and used toJson method of Gson class to convert employee List into JSON structure.Run above program and see the output, we will get compact JSON structure.Now uncomment last line of the code and run it again. This time outcome is formatted and prettyprint JSON is displayed on console. For more details How to pretty print JSON in java ?


1 Comments

Previous Post Next Post