我正在开发一个提供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?
(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的任何建议都将非常感激。
答案 0 :(得分:3)
使用zlib压缩网格。所以这就是我使用的解决方案:
(defn zlib-decompress
[input]
(with-open [input (-> input io/input-stream InflaterInputStream.)]
(slurp input)))
此函数返回json的字符串表示形式,因此当我将响应的内容类型设置为“application / json”时,一切正常。
答案 1 :(得分:2)
您正在尝试阅读GZIP压缩数据。您可以尝试使用以下内容:
(java.io.BufferedInputStream.
(java.util.zip.GZIPInputStream.
(new java.io.ByteArrayInputStream (:grid (first grid)))))
在显示之前将其解压缩。