2014-04-05 109 views
0

我正在使用SQL Korma在數據庫上運行一些簡單示例,並試圖使用Cheshire將其轉換爲JSON。將SQL Korma結果轉換爲json

這個效果很好,當我只有1個記錄返回,但是當我有多於1個結果時拋出一個錯誤。

這裏是2層的功能:

(defn get-room [id] 
    (first (select room 
      (where {:id id}) 
      (limit 1)))) 

(defn get-rooms [] 
    (select room)) 

和數據:

(def x get-rooms) 

(def y (get-room 1)) 

X是類型testproj.models.db的:

(x) 
=> [{:created_on "2014-04-05 13:19:47", :id 1, :description "Room 1"} {:created_on "2014-04-05 13:20:17", :id 2, :description "Room 2"} {:created_on "2014-04-05 13:20:20", :id 3, :description "Room 3"}] 

因爲y是一個HashMap:

(pr-str y) 
=> "{:created_on \"2014-04-05 13:19:47\", :id 1, :description \"Room 1\"}" 

嘗試轉換成JSON:

(cheshire.core/generate-string x) 
JsonGenerationException Cannot JSON encode object of class: class testproj.models.db$get_rooms: [email protected] cheshire.generate/generate (generate.clj:147) 

(cheshire.core/generate-string y) 
=> "{\"created_on\":\"2014-04-05 13:19:47\",\"id\":1,\"description\":\"Room 1\"}" 

基於記錄的金額爲何咖喱返回不同類型的(這將幫助我更好地理解這種),其次 - 我應該怎麼去呢?

回答

2

看來你錯過了一個函數調用。試試這個:

(cheshire.core/generate-string (x)) 
+0

謝謝 - 你能否迅速解釋爲什麼這需要在函數調用?這是由於x是一個詭計嗎? – Longestline

+1

您將x綁定到函數,而不是函數調用的結果。您應該將x更改爲(def x(get-rooms)),並將(generate-string x) – NielsK