Skip to content

Instantly share code, notes, and snippets.

@treo
Created May 17, 2015 19:47
Show Gist options
  • Save treo/faed20d9275276128cc8 to your computer and use it in GitHub Desktop.
Save treo/faed20d9275276128cc8 to your computer and use it in GitHub Desktop.
Simple example how the gson streaming api might be used from clojure.
(import com.google.gson.stream.JsonReader)
(import com.google.gson.Gson)
(def data "[{\"id\":2,\"name\":\"Thing1\"},{\"id\":3,\"name\":\"Thing2\"},{\"id\":4,\"name\":\"Thing3\"}]")
(def gson (Gson.))
(defrecord example [id name])
(defn to-record [java-map]
(map->example (into {} (map
(juxt
#(keyword (key %))
#(val %))
java-map))))
(defn readJsonStream [in]
(let [reader (JsonReader. in)]
(do
(.beginArray reader)
(loop [data []]
(if (.hasNext reader)
(recur (conj data (to-record (.fromJson gson reader example))))
(do (doto reader
(.endArray)
(.close))
data))))))
(readJsonStream (java.io.StringReader. data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment