【问题标题】:How to convert korma select results to json for a rest service (compojure)?如何将 korma 选择结果转换为 json 用于休息服务(组合)?
【发布时间】:2015-02-18 02:56:20
【问题描述】:

我正在使用 compojure、cheshire 和 korma(以及 postgre db)来创建休息服务。 我创建了一个包含两个字符串字段(名称和描述)的表,结构如下:

(defentity posts
  (pk :id)
  (table :posts)
  (entity-fields :name :description))

我可以在这个表中插入记录,但是当我尝试执行时

(defn get-all-posts [] 
  (select posts))

并从服务器返回结果

defroutes app-routes
 (GET "/" [] (get-start))
 (context "/posts" []
   (GET "/" [] (get-all-posts))
 ...

我收到这样的错误: java.lang.IllegalArgumentException 没有方法的实现::协议渲染:#'compojure.response/Renderable 为类找到:clojure.lang.PersistentVector

正如我所见,我需要将帖子集合转换为 json。怎么做?

【问题讨论】:

    标签: clojure compojure korma sqlkorma


    【解决方案1】:

    响铃回复可以是either a map or a string。如果它们是映射,那么它们使用一些键,例如 :status 和 :body 来定义响应并设置 cookie 等。您可能希望通过包装对 @ 的调用将响应从 Clojure 序列 (edn) 显式转换为 JSON 987654322@ in generate-string(因为您使用的是柴郡):

     {:status 200
      :content-type "application/json; charset=UTF-8"
      :body (cheshire/generate-string (get-all-posts))}
    

    当您使用它时,指定内容类型和响应代码不会有什么坏处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      相关资源
      最近更新 更多