## Serializing Clojure Datastructures

I’ve been trying to figure out how best to serialize data structures in Clojure, and discovered a couple of methods to do so. (Main reference thanks to a thread on the Clojure Google Group here )

(def box {:a 1 :b 2})

(defn serialize [o filename]
(with-open [outp (-> (File. filename) java.io.FileOutputStream. java.io.ObjectOutputStream.)]
(.writeObject outp o)))

(defn deserialize [filename]
(with-open [inp (-> (File. filename) java.io.FileInputStream. java.io.ObjectInputStream.)]
(.readObject inp)))

(serialize box "/tmp/ob1.dat")
(deserialize "/tmp/ob1.dat")


This works well for any Clojure data structure that is serializable. However, my objective is slightly more intricate – I’d like to serialize records that are actually refs. I see a few options for this,

– Either use a method that puts a record into a ref, rather than a ref into a record and then use the serializable, top level map
– Write my own serializer to print this to a file using clojure+read
– Use Java serialization functions directly.

Thoughts?