2017-10-21 190 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))))