Search code examples
jsonclojureclojure-contrib

How do I extend clojure.contribs json writer to serialize other classes


I need to create JSON objects from clojure maps that store things like clojure vars. The base implementation throws this kind of error when it sees them:

java.lang.Exception: Don't know how to write JSON of class clojure.lang.Var

Can anybody point me to sample code on how to extend the capabilities of the JSON writer?

Thanks.


Solution

  • Well, I figured out the answer. There's another SO question that answers it partially: How to map clojure code to and from JSON?

    But here's the code that worked for me:

    (defn- write-json-clojure-lang-var [x #^PrintWriter out]
    (.print out (json-str (str x))))
    
    (extend clojure.lang.Var clojure.contrib.json/Write-JSON
        {:write-json write-json-clojure-lang-var})
    

    Note that all I wanted to do is just render a string version of which Var I'm referring to. You could, of course, do many other things...