Thursday, 21 April 2016

Genson: Convert JSON to Java object

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

Step 2: Use deserialize method to convert json to a specific object.
genson.deserialize(json, clazz);
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;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=")
    .append(firstName).append(", lastName=").append(lastName)
    .append(", password=").append(password).append("]");
  return builder.toString();
 }

}

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 static Object deserializeJson(String json, Class<?> clazz) {
  return genson.deserialize(json, clazz);
 }
}

public class Test {

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

  emp.setId("E432156");
  emp.setFirstName("Hari krishna");
  emp.setLastName("Gurram");
  emp.setPassword("Password123");

  String json = JSONUtil.getJson(emp);
  System.out.println(json);

  Employee emp1 = (Employee) JSONUtil.deserializeJson(json,
    Employee.class);

  System.out.println(emp1);
 }
}

Output
{"firstName":"Hari krishna","id":"E432156","lastName":"Gurram","password":"Password123"}
Employee [id=E432156, firstName=Hari krishna, lastName=Gurram, password=Password123]



Previous                                                 Next                                                 Home

No comments:

Post a Comment