Showing posts with label Convert JSON to Java Object using Google Gson library. Show all posts
Showing posts with label Convert JSON to Java Object using Google Gson library. Show all posts

Convert JSON to Java Object using Google Gson library


In earlier tutorial we have seen how to convert Java Object to JSON. Lets take same example and try to convert JSON to Java Object using Google Gson library. The JSON output of earlier tutorial will be saved in file and will use same JSON file for this sample demo.

pom.xml

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>


 Company.java

import java.util.ArrayList;
import java.util.List;

public class Company {

 private List<String> employeeNames = new ArrayList<String>();
 
 private String companyName;
 
 private String companyAddress;
 
 private String domain;

 public List<String> getEmployeeNames() {
  return employeeNames;
 }

 public void setEmployeeNames(List<String> employeeNames) {
  this.employeeNames = employeeNames;
 }

 public String getCompanyName() {
  return companyName;
 }

 public void setCompanyName(String companyName) {
  this.companyName = companyName;
 }

 public String getCompanyAddress() {
  return companyAddress;
 }

 public void setCompanyAddress(String companyAddress) {
  this.companyAddress = companyAddress;
 }

 public String getDomain() {
  return domain;
 }

 public void setDomain(String domain) {
  this.domain = domain;
 } 
}


 company.json File:

{"employeeNames":["Steve","Jobs","Gates","Gary"],"companyName":"ABC Infotech","companyAddress":"Bangalore, India","domain":"Media"}


 JSONTesting.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.Gson;

public class JSONTesting {
 
 public static void main(String[] args) {
  
  try {
  
   BufferedReader br = new BufferedReader( new FileReader("c:\\ASIC\\company.json"));
  
   Company obj = new Gson().fromJson(br, Company.class);

   System.out.println("Company Name    : "+obj.getCompanyName());
   System.out.println("Employee Names  : " + obj.getEmployeeNames());
   System.out.println("Company Address : "+obj.getCompanyAddress());
   System.out.println("Domain          : "+obj.getDomain());
   
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


 OUTPUT:

Convert JSON to Java Object using Google Gson library