Showing posts with label Java Object to JSON. Show all posts
Showing posts with label Java Object to JSON. Show all posts

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


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;

public class JSONTesting {
    public static void main( String[] args ) {
     Company obj = new Company();
     obj.setCompanyName("ABC Infotech");
     obj.setCompanyAddress("Bangalore, India");
     Gson gson = new Gson();
        //Converts Java Object to JSON
     String json = gson.toJson(obj);


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