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:
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.
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:
Mirroring the code above, this writes a JSON document containing an array of messages. It benefits from the memory-efficiency of streaming and the conciseness of an object model:
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!