Wednesday 8 October 2014

Serialize and Deserialize java Object

To Serialize and De-serialize java Object

Serialization is nothing but converting an object into a sequence of bytes(here we are encrypting using BASE64Encoder), which can be persisted database or save in a file on disc. And Creating Java object from sequence of bytes which is save in the file is called Deserialize

Your class must be implement Serializable interface in order to Serialize or Deserialize.
Serializable is a marker interface that adds serializable behaviour to the class implementing it.


Here We are going to serialize with sun.misc.BASE64Encoder to secure encrypt, So create encrypt and decrypt objects in your main class;

    static private BASE64Encoder encode = new BASE64Encoder();
    static private BASE64Decoder decode = new BASE64Decoder();




Call objectToSerialize method to serialize your any object which is implemented Serializable interface.

    static public String objectToSerialize(Object obj) {
        String out = null;
        if (obj != null) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);
                out = encode.encode(baos.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }       
        return out;
    }
                     


Call derializeToObject method to Deserialize your String to again Java Object.

    static public Object SToO(String str) {
        Object out = null;
        if (str != null) {
            try {

                ByteArrayInputStream bios = new ByteArrayInputStream(decode.decodeBuffer(str));
                ObjectInputStream ois = new ObjectInputStream(bios);
                out = ois.readObject();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        }      
        return out;
    }


Thats it:

No comments:

Post a Comment