Jackson Streaming API

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Internal

Overview

The Streaming API reads and writes JSON as a series of discrete events, in a mode called "incremental parsing/generation". The concepts behind the Streaming API are similar to those of StAX. The Streaming API has the lowest overhead and its the fastest of all methods. The other two methods (Tree Model and Data Binding) are built in top of it. However, this is not the most convenient method, because is relatively low level. All content to read or write has to be processed in the order the input comes or the output has to go out. Random access is not possible. Also, no Java objects are created, unless specifically requested, and even then only very basic types are supported: String and byte[].

The central elements of the Streaming API are the parsers (org.codehaus.jackson.JsonParser) that are used for reading JSON content, and the generators (org.codehaus.jackson.JsonGenerator) that are used for writing Java state out as JSON.

JSON Parsing with Streaming API

JSON content is parsed with a parser (org.codehaus.jackson.JsonParser).

JsonParser instances are created using factory methods of a JsonFactory instance. Once created, they are invoked in a loop, and they identify JsonTokens in the input content:

while(!parser.isClosed()) {

    JsonToken token = parser.nextToken();

    ...
}

According to the documentation, nextToken() is the main iteration method, which will advance stream enough to determine type of the next token, if any. Upon completion, the method will return a JsonToken instance identifying the token that has just been identified. JsonToken is an enumeration, which describe all possible types of tokens identified by the parser.

Once the parser identified a token, the value associated with the token can be retrieved, as Object, with JsonParser.getText() and can be interpreted according to the token type.





Playground:

Writing Java State as JSON with Streaming API

Java state is written as JSON using a generator (org.codehaus.jackson.JsonGenerator).

Playground: