tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > Jodd > Commons > How to convert Byte array to Object

How to convert Byte array to Object 

Jodd is an open-source java library with lot of reusable components and feature rich utilities. This requires the library jodd-3.3.2.jar to be in classpath. The following example shows how to use ObjectUtil.byteArrayToObject() API. It converts the given byte array to object.

File Name  :  
com/bethecoder/tutorials/jodd/common/Student.java 
   
package com.bethecoder.tutorials.jodd.common;

public class Student implements java.io.Serializable {

  private static final long serialVersionUID = -5962595557796049374L;
  private String name;
  private int age;
  private String hobby;

  public Student() {
  }

  public Student(String name, int age, String hobby) {
    super();
    this.name = name;
    this.age = age;
    this.hobby = hobby;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getHobby() {
    return hobby;
  }
  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  
  public String toString() {
    return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]";
  }
}
   

File Name  :  
com/bethecoder/tutorials/jodd/encode/ByteArrayToObjectTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.jodd.encode;

import java.io.IOException;

import jodd.util.ObjectUtil;

import com.bethecoder.tutorials.jodd.common.Student;

public class ByteArrayToObjectTest {

  /**
   * @param args
   * @throws IOException 
   * @throws ClassNotFoundException 
   */
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    
    byte [] bytes = { -84, -19, 0, 5, 115, 114, 0, 44, 99, 111, 109, 46, 
          98, 101, 116, 104, 101, 99, 111, 100, 101, 114, 46, 116, 
          117, 116, 111, 114, 105, 97, 108, 115, 46, 106, 111, 100, 
          100, 46, 99, 111, 109, 109, 111, 110, 46, 83, 116, 117, 
          100, 101, 110, 116, -83, 64, -102, -18, 110, 62, -114, 
          34, 2, 0, 3, 73, 0, 3, 97, 103, 101, 76, 0, 5, 104, 111, 
          98, 98, 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, 2, 116, 0, 5, 67, 104, 101, 115, 115, 116, 0, 
          6, 83, 114, 105, 114, 97, 109
    };

    Student std = (Student) ObjectUtil.byteArrayToObject(bytes);
    System.out.println(std);
  }

}
   

It gives the following output,
Student[name = Sriram, age = 2, hobby = Chess]



 
  


  
bl  br