Tuesday 17 October 2017

Deserialize byte array to java object

In my previous post, I explained how to serialize an object to byte array. Below snippet is used to deserialize the byte array to java object.
        /* De serialize the byte array to object */
  private static Object getObject(byte[] byteArr) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bis = new ByteArrayInputStream(byteArr);
    ObjectInput in = new ObjectInputStream(bis);
    return in.readObject();
  }


Find the below working application.


Employee.java
package com.sample.model;

import java.io.Serializable;

public class Employee implements Serializable {

  private static final long serialVersionUID = 1L;
  private int id;
  private String name;
  private String country;

  public Employee(int id, String name, String country) {
    super();
    this.id = id;
    this.name = name;
    this.country = country;
  }

  public int getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  @Override
  public String toString() {
    return "Employee [id=" + id + ", name=" + name + ", country=" + country + "]";
  }

}


Test.java
package com.sample.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.sample.model.Employee;

public class Test {

  /* Serialize the object to byte array */
  private static byte[] getByteArray(Object obj) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (ObjectOutputStream os = new ObjectOutputStream(bos)) {
      os.writeObject(obj);
    }
    return bos.toByteArray();
  }

  /* De serialize the byte array to object */
  private static Object getObject(byte[] byteArr) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bis = new ByteArrayInputStream(byteArr);
    ObjectInput in = new ObjectInputStream(bis);
    return in.readObject();
  }

  public static void main(String args[]) throws IOException, ClassNotFoundException {
    Employee emp = new Employee(1, "Chamu", "India");

    byte[] serializedData = getByteArray(emp);

    Employee deserializedEmp = (Employee) getObject(serializedData);

    System.out.println("Deserialized Employee : " + deserializedEmp);
  }
}


No comments:

Post a Comment