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.



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"}



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) {


Convert JSON to Java Object using Google Gson library

No comments:
Write comments