gpt4 book ai didi

json - Clojure 使用 ring-json 编码 Joda DateTime

转载 作者:行者123 更新时间:2023-12-04 14:23:17 25 4
gpt4 key购买 nike

使用以下应用程序:

; 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

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

我的 project.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,你可以扩展它的协议(protocol)来处理序列化,那么它应该“正常工作”:

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

关于json - Clojure 使用 ring-json 编码 Joda DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46859881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com