Marshalling and Serialization

08 Mar 2011 by

Marshal object to a file

Marshal object to a file

In practice, the terms marshalling and serialization are used interchangeably to describe the process of squashing data types into a well-defined intermediate format that is suitable for transmission on a network or for storage in a file. You might be familiar with Remote Procedure Call (RPC) as the core stub function needs to marshal the argument and return value of a method before they are actually transmitted over the network.

This article, I will show you with an example of marshalling and unmarshalling a Java object. Be reminded that:

  • Not all data types can be serialized
  • User-defined class must implement Serializable interface
  • Attempt to marshal or serialize a non-serializable object will throw an Exception in Java

Example

According to the figure above, we will create:

  • A class Student.java having 2 properties namely Id and Name.
  • A class Marshalling.java to marshal or write object student to a file named Marshal.txt
  • A class Unmarshalling.java to unmarshal or read object student from a Marshal.txt file

Student.java

import java.io.Serializable;
/**
 *
 * @author http://lycog.com
 */

//Must implement Serializable
public class Student implements Serializable {
  private int _id;
  private String _name;

  public void setId(int id){
    _id = id;
  }
  public int getId(){
    return _id;
  }

  public void setName(String name){
    _name = name;
  }
  public String getName(){
    return _name;
  }
}

Marshalling.java

import java.io.*;

/**
 *
 * @author http://lycog.com
 */
public class Marshalling {
  public static void main(String[] args){
    String filename = "marshal.txt";

    try{
      ObjectOutputStream oos =
              new ObjectOutputStream(
                new FileOutputStream(filename));

      //Marshal or create sudent lycog
      Student lycog = new Student();
      lycog.setId(1);
      lycog.setName("lycog");

      //Write object lycog to file
      oos.writeObject(lycog);

      //Flush and close file
      oos.flush();
      oos.close();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
}

Unmarshalling.java

import java.io.*;
/**
 *
 * @author http://lycog.com
 */
public class Unmarshalling {
  public static void main(String[] args){
    String filename= "marshal.txt";

    try{
      ObjectInputStream ois =
              new ObjectInputStream(
                new FileInputStream(filename));

      //Unmarshalling object lycog from file
      Student lycog = (Student)ois.readObject();

      System.out.println("Student ID = " + lycog.getId());
      System.out.println("Student Name = " + lycog.getName());

      ois.close();
    }catch(ClassNotFoundException cnfe){
      cnfe.printStackTrace();
    }catch(IOException ioe){
      ioe.printStackTrace();
    }
  }
}

To see the marshalled student object, click The Content of marshalled object

No responses yet

Leave a Reply