Serialization and Deserialization in Java

Imagine that you have to send a java object to someone via a network or you want to store it in the db or in memory. If you are looking to perform any of these operations then Serialization will help you.
Serialization will transform the object to bytes so that it can be stored in the DB or memory or sent via a network. Deserialization on the other hand, will transform the bytes to the object.

In java Serialization and Deserialization can be achieved by implementing 'Serializable' interface. It is a Marker interface in which the implementing class don't have to implement any functions of the interface.

In the following example 'Student' object contains name and id. Since the object is implementing 'Serializable' interface we can define 2 methods that will serialize and deserialize.


 //Define a class that needs to be serialized and de-serialized
public class Student implements Serializable {
    String sName;
    int sId;
}




Following serializeStudent method will write the object to the file stream that is named as 'Student.ser'. Similarly, deserializeStudent method will read the file stream and convert it to the Student object. 


Implementation:
   
//Serialize it 
public class serializeStudent {
   Student s = new Student();
   s.sName = “jack”;
   s.sId = 1;

   try {
       FileOutputStream fs = new FileOutputStream(“Student.ser”);
       ObjectOutputStream os = new ObjectOutputStream(fs);
       os.writeObject(s);
       os.close();
      }
}
 //DeSerialize it
public void deserializeStudent {
   FileInputStream fin = new FileInputStream(“FileName”);
   ObjectInputStream ion = new ObjectInputStream(fin);
   Student sObject = (student)oin.readObject();
}
You might also like:

No comments:

Post a Comment

NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...