Wednesday, 27 January 2016

Java POJO to JSON using Gson (

Java POJO to JSON using
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.

If you are using Maven then the dependency is

Step 2:

We will start by creating a simple Employee POJO class.


package net.codermag.json.examples;

public class Employee {

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

 public void setName(String name) { = name;

 public void setEmail(String email) { = email;

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



package net.codermag.json.examples;

public class EmployeeAddress {

 private String city;
 private String state;

 public void setCity(String 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.


package net.codermag.json.examples;


public class PojoToJsonExample {

 public static void main(String[] args) {

  // Setting values of the Employee POJO
  Employee emp1 = new Employee();

  EmployeeAddress address = new EmployeeAddress();
  address.setCity("New York");

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



{"name":"John","email":"","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.