Writing JSON custom types in responses

551 views
Skip to first unread message

wm.ma...@gmail.com

unread,
Dec 15, 2013, 7:42:54 AM12/15/13
to clojure-...@googlegroups.com
Hi,

I have a web-service implemented with Liberator that returns various data from a postgres database via JDBC.

I see that Liberator very helpfully automatically serialises my maps of data from the database result-sets to JSON.

This works just fine in most cases without me having to do anything.

However, I have some complex types like java.sql.Timestamp or java.util.Date that fail to get serialised.

java.lang.Exception: Don't know how to write JSON of class java.util.Date

            json.clj:367 clojure.data.json/write-generic


That's fair enough, it needs to be told how I want those classes serialised...

So with clojue.data.json, I believe there is a mechanism using :value-fn to serialise such types, but how do I plug in to Liberator to do that? Or is there something else I should be looking at?

Thanks!

Regards,

-M.

Philipp Meier

unread,
Dec 15, 2013, 4:26:42 PM12/15/13
to clojure-...@googlegroups.com
Hi,


Am Sonntag, 15. Dezember 2013 13:42:54 UTC+1 schrieb wm.ma...@gmail.com:
However, I have some complex types like java.sql.Timestamp or java.util.Date that fail to get serialised.

java.lang.Exception: Don't know how to write JSON of class java.util.Date

            json.clj:367 clojure.data.json/write-generic


That's fair enough, it needs to be told how I want those classes serialised...

So with clojue.data.json, I believe there is a mechanism using :value-fn to serialise such types, but how do I plug in to Liberator to do that? Or is there something else I should be looking at?

At the moment there is no way when you depend on liberator's automatic response generation. But you can do the following:

(defresource foo
  :handle-ok (fn [{{mt :media-type} :representation}]
                (if (= "application/json" mt)
                    (core.data.json/write-str my-data :value-fm my-value-fm)
                    (as-response my-data)))
;; my-data is the data structure you return from the handler right
;; my-value-fm is the function that serializes Date to a string


-billy.
 

Paolo Piersanti

unread,
Feb 29, 2016, 10:31:12 AM2/29/16
to Liberator
this works too
(defmethod render-map-generic "application/json"
  [data context]
  (json/write-str data :value-fn (fn [key value] (if (instance? java.sql.Timestamp value) (str value)))))

Paolo
Reply all
Reply to author
Forward
0 new messages