在这个例子中,我创建了一个简单的api,查询数据库并获取所有文档。我希望响应作为json对象返回。然而实际的输出是:{:text "some text", :title "title", :id "1"}{:text "some more text", :title "another title", :id "2"}
我对clojure很新,所以可能会遗漏一些明显的东西。
handler.clj
(ns app.handler
(:use compojure.core)
(:use cheshire.core)
(:use app.document)
(:require [compojure.handler :as handler]
[ring.middleware.json :as middleware]
[compojure.route :as route]))
(defroutes app-routes
(context "/documents" [] (defroutes documents-routes)
(GET "/" [] (list-documents)))
(route/not-found "Not Found"))
(def app
(-> (handler/api app-routes)
(middleware/wrap-json-body)
(middleware/wrap-json-response)))
storage.clj
(ns app.storage
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:require [clojure.java.jdbc :refer :all]))
(def db
{
:classname "org.sqlite.JDBC"
:subprotocol "sqlite"
:subname "src/storage/sqlite.db"
}
)
document.clj
(ns app.document
(:use app.storage)
(:use ring.util.response)
(:require [clojure.java.jdbc :refer :all]))
(defn list-documents []
(let [results (query db ["select * from documents"])]
(prn results)
(cond (empty? results)
(not_found ())
:else
(response (lazy-seq results)))))
答案 0 :(得分:2)
使用地图或身体矢量将响应转换为JSON响应的中间件。
来自wrap-json-response
的文档字符串。你给它一个序列,但它只接受地图或矢量。将(response (lazy-seq results))
更改为(response (vec results))
。
编辑:改变了我的整个答案,我误解了。