Tuesday 17 October 2017

Serialize the object to byte array

If java class implement Serializable interface, then you can use below snippet to get the byte array form of the object.

 private static byte[] getByteArray(Object obj) throws IOException {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try (ObjectOutputStream os = new ObjectOutputStream(bos)) {
   os.writeObject(obj);
  }
  return bos.toByteArray();
 }

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.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import com.sample.model.Employee;

public class Test {

 private static byte[] getByteArray(Object obj) throws IOException {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try (ObjectOutputStream os = new ObjectOutputStream(bos)) {
   os.writeObject(obj);
  }
  return bos.toByteArray();
 }

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

  byte[] serializedData = getByteArray(emp);

  for (byte b : serializedData) {
   System.out.print(b + ",");
  }
 }
}


Output

-84,-19,0,5,115,114,0,25,99,111,109,46,115,97,109,112,108,101,46,109,111,100,101,108,46,69,109,112,108,111,121,101,101,0,0,0,0,0,0,0,1,2,0,3,73,0,2,105,100,76,0,7,99,111,117,110,116,114,121,116,0,18,76,106,97,118,97,47,108,97,110,103,47,83,116,114,105,110,103,59,76,0,4,110,97,109,101,113,0,126,0,1,120,112,0,0,0,1,116,0,5,73,110,100,105,97,116,0,5,67,104,97,109,117,



No comments:

Post a Comment