Clojure使用环形json对Joda DateTime进行编码



使用以下应用程序:

; 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编码:class.org.joda.time.DateTime:2017-10-21T03:38:16.207Z

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

我的项目.clj有这些依赖关系仅供参考:

[[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"]]

如果您使用Cheshire生成JSON,您可以扩展其协议来处理序列化,那么它应该"正常工作":

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

此外,以下修改使其适用于使用时间库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))))

最新更新