Convert Java Object to JSON using Google Gson library

In this tutorial lets see how to convert Java Object to JSON using Google Json library. Its quite very easy and just by toJson() method we can convert to JSON. Lets see simple example for converting Java Object to JSON along with maven dependency for Google Gson.
Covert Java Object to JSON using Google Gson library


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

JSONTesting.java
import com.google.gson.Gson;

public class JSONTesting {
 
    public static void main( String[] args ) {
     
     Company obj = new Company();
     
     obj.getEmployeeNames().add("Steve");
     obj.getEmployeeNames().add("Jobs");
     obj.getEmployeeNames().add("Gates");
     obj.getEmployeeNames().add("Gary");
     
     obj.setCompanyName("ABC Infotech");
     obj.setCompanyAddress("Bangalore, India");
     obj.setDomain("Media");
     
     Gson gson = new Gson();
     
        //Converts Java Object to JSON
     String json = gson.toJson(obj);
     
     System.out.println(json);
    }
}


OUTPUT:


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

No comments :

Post a Comment