Serializing an object

From CodeCodex

Contents

[edit] Implementations

[edit] Java

The object to be serialized must implement java.io.Serializable. This example serializes a javax.swing.JButton object.


Object object = new javax.swing.JButton("push me");

try {
        // Serialize to a file
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
        out.writeObject(object);
        out.close();

        // Serialize to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
        out = new ObjectOutputStream(bos) ;
        out.writeObject(object);
        out.close();

        // Get the bytes of the serialized object
        byte[] buf = bos.toByteArray();
} catch (IOException e) {
        // Never leave a catch empty, even temporarily.
        e.printStackTrace();
}

[edit] OCaml

The built-in Marshal module provides serialisation. For example:

# Marshal.to_string [1;2;3;4] [];;
- : string =
"\132\149¦¾\000\000\000\t\000\000\000\004\000\000\000\012\000\000\000\012 A B C D@"

[edit] Ruby

p Marshal.dump([1, 3.141, {:one=>1, :two=>2}, true, false])
#=> "\x04\b[\ni\x06f\r3.141\x00\xE3T{\a:\bonei\x06:\btwoi\aTF"