Thursday 21 April 2016

Genson: Object serialization and deserialization

Genson API provides methods to serialize an object to a file and de-serialize from file.

Following methods are used to serialize an object to a file (or) stream.

public void serialize(Object object, Writer writer)
public void serialize(Object object, OutputStream output)

Following methods are used to de-serialize data from file (or) stream.

public <T> T deserialize(Reader reader, Class<T> toType)
public <T> T deserialize(InputStream input, Class<T> toType)
public <T> T deserialize(InputStream input, GenericType<T> toType)


Following example shows you how to serialize an Employee object to a file and get it back.
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;
 }

 @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 java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.owlike.genson.Genson;

public class Test {

 public static void main(String args[]) throws FileNotFoundException,
   IOException {
  Employee emp1 = new Employee();

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

  Genson genson = new Genson();

  try (FileOutputStream fos = new FileOutputStream("ser.out");) {
   genson.serialize(emp1, fos);

  }

  try (FileInputStream fin = new FileInputStream("ser.out");) {
   Employee emp = genson.deserialize(fin, Employee.class);
   System.out.println(emp);
  }

 }
}

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




Previous                                                 Next                                                 Home

No comments:

Post a Comment