Thursday, 21 April 2016

Genson: Convert Java object to Json

In this post, I am going to explain how to convert Java object to json.

Step 1: Get Genson instance.
Genson genson = new Genson();

Step 2: Serializes the object into a json string.
genson.serialize(obj);
public class Employee {
 private String id;
 private String firstName;
 private String lastName;
 private String password;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

}

import com.owlike.genson.Genson;

public class JSONUtil {
 private static Genson genson = new Genson();

 public static String getJson(Object obj) {
  return genson.serialize(obj);
 }
}

public class Test {
 public static void main(String args[]) {
  Employee emp = new Employee();

  emp.setFirstName("Hari Krishna");
  emp.setId("E432156");
  emp.setPassword("password123");

  System.out.println(JSONUtil.getJson(emp));
 }
}

Output
{"firstName":"Hari Krishna","id":"E432156","lastName":null,"password":"password123"}


Observe the output, it converts employee object to json string. One problem in this program is, it is not ignoring  null fields. I will explain how to ignore null fields while serializing an object later.


Previous                                                 Next                                                 Home

No comments:

Post a Comment