Back

JSONWriter (clj)

(source)

protocol

Examples

kyleburton/clj-etl-utils
(ns clj-etl-utils.json
  (:import
   [java.sql Timestamp]
   [java.io PrintWriter]
   [org.joda.time DateTime]
   [org.joda.time.format ISODateTimeFormat])
  (:require
   [clojure.data.json :as json]))


(extend java.sql.Timestamp json/JSONWriter
        {:-write (fn [x #^PrintWriter out]
                   (.print out "\"")
                   (.print out
                           (.print (ISODateTimeFormat/dateTime )
                                   (org.joda.time.DateTime. x)))
                   (.print out "\""))})

(extend org.joda.time.DateTime json/JSONWriter
        {:-write (fn [x #^PrintWriter out]
                   (.print out "\"")
                   (.print out (.toString x))
                   (.print out "\""))})

(extend java.util.Date json/JSONWriter
        {:-write (fn [x #^PrintWriter out]
                   (.print out "\"")
                   (.print out (.toString (org.joda.time.DateTime. x)))
                   (.print out "\""))})

(extend clojure.lang.Fn json/JSONWriter
        {:-write (fn [x #^PrintWriter out]
                   (.print out "\"")
                   (.print out (.toString x))
                   (.print out "\""))})
(comment
  (org.joda.time.DateTime. (java.util.Date.))
  (clojure.data.json/json-str (java.util.Date.))
  (clojure.data.json/json-str (java.sql.Timestamp. (.getTime (java.util.Date.))))
clojurewerkz/support
(try
  (require 'clojure.data.json)
  (catch Throwable t
    false))


;; all this madness would not be necessary if some people cared about backwards
;; compatiblity of the libraries they maintain. Shame on the clojure.data.json maintainer. MK.
(compile-if (and (find-ns 'clojure.data.json)
                 clojure.data.json/JSONWriter)
            (try
              ;; now try extending clojure.data.json 0.2.x protocol
              (extend-protocol clojure.data.json/JSONWriter
                org.joda.time.DateTime
                (-write [^DateTime object out]
                  (clojure.data.json/write (.print (ISODateTimeFormat/dateTime) ^ReadableInstant object) out))