开发者

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 p开发者_如何学Gooint me to sample code on how to extend the capabilities of the JSON writer?

Thanks.


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...


An update to the answer from zippy for those of us using the newer clojure.data.json. This is code that will work with the updated/new library:

(defn- write-json-clojure-lang-var [x #^PrintWriter out]
    (.print out (json-str (str x))))

(extend clojure.lang.Var clojure.data.json/JSONWriter
    {:-write write-json-clojure-lang-var})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜