Clojure 使用ring-json 编码 Joda DateTime

问题描述 投票:0回答:3

使用以下应用程序:

; 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"]]
json clojure jodatime ring
3个回答
10
投票

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

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

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

0
投票

另一种方法可以做与泰勒伍兹回答相同的事情:

(cheshire.generate/add-encoder java.time.LocalDate cheshire.generate/encode-str)
© www.soinside.com 2019 - 2024. All rights reserved.