How to convert Object to Byte array
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.objectToByteArray() API.
It converts the given object to a byte array.
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 + "]" ;
}
}
package com.bethecoder.tutorials.jodd.encode;
import java.io.IOException;
import java.util.Arrays;
import com.bethecoder.tutorials.jodd.common.Student;
import jodd.util.ObjectUtil;
public class ObjectToByteArrayTest {
/**
* @param args
* @throws IOException
*/
public static void main ( String [] args ) throws IOException {
Student std = new Student ( "Sriram" , 2 , "Chess" ) ;
byte [] bytes = ObjectUtil.objectToByteArray ( std ) ;
System.out.println ( Arrays.toString ( bytes )) ;
}
}
It gives the following output,
[-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]