我正在开发一个提供 json 文件的 Compojure 应用程序。我正在使用 clojure.java.jdbc 库从 sqlite 数据库中检索文件:
(defn grid-result [z x y]
(j/with-connection db-specs
(j/with-query-results results ["SELECT grid FROM grids WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?" z x y]
(doall results))))
查询的结果是这样的:
({:grid #<byte[] [B@7e88dd33>})
为了将其显示为 json,我更新了标题,并将查询结果剥离为字节数组并使用 ByteArrayInputStream:
(defn grid-response [grid]
{:status 200
:headers {"Content-Type" "application/json"}
:body (new java.io.ByteArrayInputStream (:grid (first grid)))})
这是处理请求的方式:
(defroutes app-routes
(GET "/api/:z/:x/:y.grid.json" [z x y] (grid-response (grid-result z x y))
(route/not-found "Page not found"))
以上所有结果:
"xœ«VJ/ÊLQ²ŠVR (éŒ1jĨ£FŒ1jĨ£FŒ1jĨÄEÊPP¨¨ªQl„
Å®€ƒQ#F5b¤«£”ZYÈ�gh`jndaXƒf†æ0†Œa¨[�7ð+k"
我试图检索的 Json 格式为:
grid({"keys": ["""], "data": {"105803": {"predicti_9": 0.0257, "prediction": "3B2", "OA01CDOLD": "15UFGH0011"}, "106178": {"predicti_9": 0.0265, "prediction": "6B1", "OA01CDOLD": "15UHFE0001"}, "106171": {"predicti_9": 0.0257, "prediction": "3B2", "OA01CDOLD": "15UHFC0001"}, "105721": {"predicti_9": 0.0257, "prediction": "3B2", "OA01CDOLD": "15UFGC0013"}, "106170": {"predicti_9": 0.0257, "prediction": "3B2", "OA01CDOLD": "15UHFB0001"}}, "grid": [" ", " "]});
我也尝试过:
更改了网格响应函数以将字节数组转换为字符串:
:body (String. (:grid (first grid)) "UTF-8")
结果为((使用 UTF-8 或不使用):
x??VJ/?LQ??VR?(?1j??F?1j??F?1j??E?PP????Ql?
???Q#F?5b?????ZY?�gh`jndaX?f??0??a?[�7?
将每个字符映射到 str:
(apply str (map #(char (bit-and % 255)) (:grid (first grid))))
结果是:
xœ«VJ/ÊLQ²ŠVR (éŒ1jĨ£FŒ1jĨ£FŒ1jĨÄEÊPP¨¨ªQl„
Å®€ƒQ#F5b¤«£”ZYÈ�gh`jndaXƒf†æ0†Œa¨[�7ð+k
(与 ava.io.ByteArrayInputStream 相同)。
任何关于如何将该字节流转换为 json 的建议将不胜感激。