Deserializing an object

From CodeCodex

Implementations[edit]

Erlang[edit]

It reads a file in the binary form and it displays the original.

-module(codex).
-export([deserialize/1]).
deserialize(Filename) ->
    Size = filelib:file_size(Filename),
    {ok, IoDevice} = file:open(Filename, [read, binary]),
    {ok, Data} = file:read(IoDevice, Size),
    io:format("~p~n", [Data]),
    io:format("~p~n", [binary_to_term(Data)]),
    file:close(IoDevice).

For example:

1> codex:deserialize("binary.dat").                 
<<131,104,4,97,1,107,0,1,2,100,0,4,116,114,117,101,107,0,3,97,98,99>>
{1,[2],true,"abc"}
ok

Java[edit]

This example deserializes a javax.swing.JButton object.

    try {
        // Deserialize from a file
        File file = new File("filename.ser");
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        // Deserialize the object
        javax.swing.JButton button = (javax.swing.JButton) in.readObject();
        in.close();
    
        // Get some byte array data
        byte[] bytes = getBytesFromFile(file);
        // see e36 Reading a File into a Byte Array for the implementation of this method
    
        // Deserialize from a byte array
        in = new ObjectInputStream(new ByteArrayInputStream(bytes));
        button = (javax.swing.JButton) in.readObject();
        in.close();
    } catch (ClassNotFoundException e) {
    } catch (IOException e) {
    }

OCaml[edit]

# (Marshal.from_string
     "\132\149\166\190\000\000\000\t\000\000\000\004\000\000\000\012\000\000\000\012\160A\160B\160C\160D@"
     0 : int list);;
- : int list = [1; 2; 3; 4]

Ruby[edit]

string = Marshal.dump([1, 2, 3, 4])
p string                #=> "\x04\b[\ti\x06i\ai\bi\t"
p Marshal.load(string)  #=> [1, 2, 3, 4]