2017-10-21 193 views
4

用下面的程序:Clojure的編碼喬達日期時間與環JSON

; src/webapp/core.clj 
(ns webapp.core 
    (:require [compojure.core :refer [defroutes GET]] 
      [ring.middleware.json :as mid-json] 
      [clj-time.jdbc])) 

(defn foo [request] 
    {:body {:now (org.joda.time.DateTime/now)}}) 

(defroutes routes 
    (GET "/foo" [] foo)) 

(def app 
    (-> routes 
     (mid-json/wrap-json-response))) 

擊中/ foo的端點給了我這個錯誤:

com.fasterxml.jackson.core.JsonGenerationException:不能JSON編碼對象的類:類org.joda.time.DateTime:2017-10-21T03:38:16.207Z

有沒有一種簡單的方法來獲取ringjson編碼DateTime對象?我是否需要編寫自己的中間件才能將其轉換爲一個字符串?如果是這樣,我該怎麼做? (我從來沒有寫過鈴聲中間件)。

我project.clj有這些依賴FYI:

[[org.clojure/clojure "1.8.0"] 
[org.clojure/java.jdbc "0.6.1"] 
[ring/ring-jetty-adapter "1.4.0"] 
[compojure "1.4.0"] 
[ring/ring-json "0.4.0"] 
[clj-time "0.14.0"]] 

回答

3

如果您使用柴生成JSON,你可以擴展它的協議來處理序列化,那麼它應該「只是工作」:

(extend-protocol cheshire.generate/JSONable 
    org.joda.time.DateTime 
    (to-json [dt gen] 
    (cheshire.generate/write-string gen (str dt))))