【问题标题】:Clojure encode Joda DateTime with ring-jsonClojure 使用 ring-json 编码 Joda DateTime
【发布时间】:2018-04-02 06:16:41
【问题描述】:

使用以下应用:

; 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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-20
        • 1970-01-01
        • 2015-10-06
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多