title: Converting byte array to json in Compojure
body: <p>I'm working on a Compojure application that serves json files. I'm using clojure.java.jdbc library to retrieve the files from sqlite database:</p>
  
  <pre><code>(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))))
  </code></pre>
  
  <p>The result of the query is this:</p>
  
  <pre><code>({:grid #&lt;byte[] [B@7e88dd33&gt;})
  </code></pre>
  
  <p>In order to display it as json, I update the headers, and strip the query result to byte array and use ByteArrayInputStream:</p>
  
  <pre><code>(defn grid-response [grid]
    {:status 200
     :headers {"Content-Type" "application/json"}
     :body (new java.io.ByteArrayInputStream (:grid (first grid)))})
  </code></pre>
  
  <p>This is how the request is handled:</p>
  
  <pre><code>(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"))
  </code></pre>
  
  <p>All above results in:</p>
  
  <pre><code>"xœ«VJ/ÊLQ²ŠVR (éŒ1jÄ¨£FŒ1jÄ¨£FŒ1jÄ¨ÄEÊPP¨¨ªQl„
  Å®€ƒQ#F5b¤«£”ZYÈ�gh`jndaXƒf†æ0†Œa¨[�7ð+k"
  </code></pre>
  
  <p>Json that I'm trying to retrieve has a format of:</p>
  
  <pre><code>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": ["  ", "  "]});
  </code></pre>
  
  <p>What I've also tried:</p>
  
  <h2>Changed grid-response function to convert byte array to String:</h2>
  
  <pre><code>:body (String. (:grid (first grid)) "UTF-8")
  </code></pre>
  
  <p>Results in ((with UTF-8 or without):</p>
  
  <pre><code>x??VJ/?LQ??VR?(?1j??F?1j??F?1j??E?PP????Ql?
  ???Q#F?5b?????ZY?�gh`jndaX?f??0??a?[�7?
  </code></pre>
  
  <h2>Mapped each char to str:</h2>
  
  <pre><code>(apply str (map #(char (bit-and % 255)) (:grid (first grid))))
  </code></pre>
  
  <p>Results in:</p>
  
  <pre><code>xœ«VJ/ÊLQ²ŠVR (éŒ1jÄ¨£FŒ1jÄ¨£FŒ1jÄ¨ÄEÊPP¨¨ªQl„
  Å®€ƒQ#F5b¤«£”ZYÈ�gh`jndaXƒf†æ0†Œa¨[�7ð+k
  </code></pre>
  
  <p>(Same as with ava.io.ByteArrayInputStream).</p>
  
  <p>Any advice on how to convert that byte stream to json will be greatly appreciated.</p>