Wednesday, 27 January 2016

Java POJO to JSON using Gson (com.google.gson.Gson)


Java POJO to JSON using com.google.gson.Gson
In many daily development scenarios we come across  situations where we need to convert a JAVA POJO into JSON.

There are many ways that we can use to do so. The following article shows hoe to convert a POJO class into JSON using the Google Gson API.

Step 1:

Download the Gson_2.5.jar file form the link below and place it in your build path.
http://mvnrepository.com/artifact/com.google.code.gson/gson/2.5

If you are using Maven then the dependency is




Step 2:


We will start by creating a simple Employee POJO class.

Class: Employee.java

package net.codermag.json.examples;

public class Employee {

 private String name;
 private String email;
 private EmployeeAddress address;

 public void setName(String name) {
  this.name = name;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public void setAddress(EmployeeAddress address) {
  this.address = address;
 }

}

Class: EmployeeAddress.java

package net.codermag.json.examples;

public class EmployeeAddress {

 private String city;
 private String state;

 public void setCity(String city) {
  this.city = city;
 }

 public void setState(String state) {
  this.state = state;
 }
}


Now that we have the structure of the POJO ready we can now convert the Employee POJO into JSON by running the following code sample.

Class: PojoToJsonExample.java

package net.codermag.json.examples;

import com.google.gson.Gson;

public class PojoToJsonExample {

 public static void main(String[] args) {

  // Setting values of the Employee POJO
  Employee emp1 = new Employee();
  emp1.setName("John");
  emp1.setEmail("John@mail.com");

  EmployeeAddress address = new EmployeeAddress();
  address.setCity("New York");
  address.setState("USA");
  emp1.setAddress(address);

  // Instantiating GSON
  Gson gson = new Gson();
  String json = gson.toJson(emp1);

  System.out.println(json);
 }
}



Output:

{"name":"John","email":"John@mail.com","address":{"city":"New York","state":"USA"}}


No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.