Hi,
Today i want to show you how you can serialize or deserialize an Object. I will take like example a String object, but there can be any type of Object.
To serialize an object means to make it a binary, and to deserialize it, means to make it from binary to the Object.
So let’s start.
This is the method for serializing a generic Object.
public class SerializeClass { public static byte[] serializeObject(Object o) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutput out = new ObjectOutputStream(baos); out.writeObject(o); out.close(); // Get the bytes of the serialized object byte[] buffer = baos.toByteArray(); return buffer; } catch(IOException ioe) { return null; } } public static Object deserializeObject(byte[] b) { try { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b)); Object object = in.readObject(); in.close(); return object; } catch(ClassNotFoundException cnfe) { Log.e("deserializeObject", "class not found error", cnfe); return null; } catch(IOException ioe) { Log.e("deserializeObject", "io error", ioe); return null; } } }
To call this methods you will do like this:
Your class must implement Serializable for this to work
public class MyClass implements Serializable { String text; MyClass myClass = new MyClass(); byte[] binaryObject = SerializeClass.serializeObject(myClass); MyClass deserializedMyClass = SerializeClass.deserializeObject(binaryObject);