Clojure encode Joda DateTime using ring-json

In the following application:

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

Finding the endpoint / foo gives me this error:

com.fasterxml.jackson.core.JsonGenerationException: JSON cannot encode class object: class org.joda.time.DateTime: 2017-10-21T03: 38: 16.207Z

Is there an easy way to get ring-json to encode a DateTime object? Do I have to write my own middleware to convert it, for example. line first? If so, how do I do this? (I had never written ring middleware before).

My .clj project has these FYI dependencies:

[[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"]]
+4
source share
1 answer

Cheshire JSON, , " ":

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

Source: https://habr.com/ru/post/1687922/


All Articles