Clojure用ring-json编码Joda DateTime

时间:2017-10-21 03:53:50

标签: json clojure jodatime ring

使用以下应用程序:

text.draw(at:  NSZeroPoint, withAttributes: [NSFontAttributeName: font, 
                                  NSForegroundColorAttributeName: NSColor(white: 1.0, alpha: 0.3)])

点击/ foo端点给出了这个错误:

com.fasterxml.jackson.core.JsonGenerationException:JSON不能编码类的对象:class org.joda.time.DateTime:2017-10-21T03:38:16.207Z

是否有一种简单的方法可以让ring-json对DateTime对象进行编码?我是否必须编写自己的中间件才能将其转换为例如一个字符串第一?如果是这样,我该怎么做? (我之前从未写过戒指中间件。)

我的project.clj有这些依赖关系FYI:

; 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)))

2 个答案:

答案 0 :(得分:7)

如果您正在使用Cheshire生成JSON,您可以扩展其协议以处理序列化,然后它应该"只是工作":

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

答案 1 :(得分:0)

此外,以下修改使它适用于使用时间库tick.alpha.api的项目。我遇到了错误

#error {:cause Cannot JSON encode object of class:
 class java.time.Instant: 2019-10-23T00:31:40.668Z
 :via
 [{:type com.fasterxml.jackson.core.JsonGenerationException
   :message Cannot JSON encode object of class:
 class java.time.Instant: 2019-10-23T00:31:40.668Z
   :at [cheshire.generate$generate invokeStatic generate.clj 152]}]

在文件db/core.clj中添加以下内容为我解决了该问题。

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