Streaming

Gson can read and write JSON as an object model or stream. Gson's object model uses the same approach as XML DOM; Gson's streams uses the same approach as XML pull parsers. Gson doesn't support event-based models like SAX.

Object model access is available via the JsonElement class hierarchy. These classes operate on a JSON document as a navigable object tree. This model is easy to use and capable because it permits random read and write access to the entire JSON document. Code written using object models is both concise and intention revealing. Gson's capable data binding is built upon its flexible object model.

Streaming access to JSON documents is available via the JsonReader and JsonWriter classes which were added in Gson 1.6. These classes operate on a JSON document as a sequence of tokens that are traversed in depth-first order. Because the streams operate on one token at a time, they impose minimal memory overhead.

Most applications should use only the object model API. JSON streaming is useful in just a few situations:

When it is impossible or undesirable to load the entire object model into memory. This is most relevant on mobile platforms where memory is limited.

When it is necessary to read or write a document before it is completely available.

Gson also supports mixed streaming & object model access. This lets your application have the best of both worlds: the productivity of object model access with the efficiency of streaming. To mix modes, first create a stream. Then use Gson.fromJson() and Gson.toJson() to read from and write to the stream.

Mixed Reads Example

This code reads a JSON document containing an array of messages. It steps through array elements as a stream to avoid loading the complete document into memory. It is concise because it uses Gson’s object-model to parse the individual messages:

Prettyprint Example

JsonPrettyPrint.java reads a stream of tokens from a JsonReader and writes them back to a JsonWriter. It uses peek() to preview the next token, reads it, writes it, and loops until the token stream is exhausted. Most applications will take more interesting actions based on the content of the tokens!