The same fix for data.json compatibility we had in clojurewerkz.support.json

This commit is contained in:
Michael S. Klishin 2012-11-09 02:17:45 +04:00
parent 47aabed2e4
commit c5e2c78ed0
2 changed files with 43 additions and 19 deletions

View file

@ -12,24 +12,56 @@
monger.json
(:import org.bson.types.ObjectId))
;;
;; Implementation
;;
;; copied from clojure.reducers
(defmacro ^:private compile-if
"Evaluate `exp` and if it returns logical true and doesn't error, expand to
`then`. Else expand to `else`.
(compile-if (Class/forName \"java.util.concurrent.ForkJoinTask\")
(do-cool-stuff-with-fork-join)
(fall-back-to-executor-services))"
[exp then else]
(if (try (eval exp)
(catch Throwable _ false))
`(do ~then)
`(do ~else)))
;;
;; API
;;
(require 'clojurewerkz.support.json)
(try
(require 'clojure.data.json)
(catch Throwable t
;; 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
(extend-protocol clojure.data.json/JSONWriter
ObjectId
(-write [^ObjectId object out]
(clojure.data.json/write (.toString object) out)))
(catch Throwable _
false))
(comment "Nothing to do, clojure.data.json is not available"))
(try
(compile-if (and (find-ns 'clojure.data.json)
clojure.data.json/Write-JSON)
(try
(extend-protocol clojure.data.json/Write-JSON
ObjectId
(write-json [^ObjectId object out escape-unicode?]
(clojure.data.json/write-json (.toString object) out escape-unicode?)))
(catch Throwable _
false))
(comment "Nothing to do, clojure.data.json 0.1.x is not available"))
(try
(require 'cheshire.custom)

View file

@ -6,7 +6,6 @@
com.mongodb.DBObject)
(:require monger.json
monger.joda-time
[clojure.data.json :as json]
[clj-time.core :as t]
[cheshire.custom :as json2]))
@ -14,20 +13,13 @@
(deftest ^{:integration true} serialization-of-joda-datetime-to-json
(let [dt (t/date-time 2011 10 13 23 55 0)]
(is (= "\"2011-10-13T23:55:00.000Z\""
(json/json-str dt)
(json2/encode dt)))))
(deftest ^{:integration true} serialization-of-joda-date-to-json
(let [d (.toDate (t/date-time 2011 10 13 23 55 0))]
(is (= "\"2011-10-13T23:55:00.000Z\""
(json/json-str d)))
(is (= "\"2011-10-13T23:55:00Z\""
(json2/encode d)))))
(deftest ^{:integration true} serialization-of-object-id-to-json-with-clojure-data-json
(is (= "\"4ec2d1a6b55634a935ea4ac8\"" (json/json-str (ObjectId. "4ec2d1a6b55634a935ea4ac8")))))
(deftest ^{:integration true} conversion-of-joda-datetime-to-db-object
(let [d (to-db-object (t/date-time 2011 10 13 23 55 0))]
(is (instance? java.util.Date d))