Thursday 21 April 2016

Genson: POJO constructor with arguments

If your POJO has parameterized constructors and don’t provide default constructor, then while de-serializing you will get following kind of error.

Exception in thread "main" com.owlike.genson.JsonBindingException: Could not deserialize to type class genson_tutorial.Employee
         at com.owlike.genson.Genson.deserialize(Genson.java:384)
         at com.owlike.genson.Genson.deserialize(Genson.java:299)

To get rid of this error, you need to create Genson instance like below.


Genson genson = new GensonBuilder().useConstructorWithArguments(true).create();
import com.owlike.genson.annotation.JsonIgnore;

public class Employee {
  private String id;
  private String firstName;
  private String lastName;
  @JsonIgnore
  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;
  }

  @JsonIgnore
  public String getPassword() {
    return password;
  }

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

  public Employee(String firstName) {
    this.firstName = firstName;
  }

  @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;
import com.owlike.genson.GensonBuilder;

public class Test {

  public static void main(String args[]) {
    Employee emp1 = new Employee("Hari");

    emp1.setId("E432156");
    emp1.setFirstName("Hari krishna");
    emp1.setPassword("Password123");

    String json = JSONUtil.getJson(emp1);

    Genson genson = new GensonBuilder().useConstructorWithArguments(true)
        .create();

    Employee emp = genson.deserialize(json, Employee.class);

    System.out.println(emp);
  }
}


Output
Employee [id=E432156, firstName=Hari krishna, lastName=null, password=null]



Previous                                                 Next                                                 Home

No comments:

Post a Comment