Jackson Streaming API: Difference between revisions
Line 18: | Line 18: | ||
JSON content is parsed with a ''parser'' (<tt>org.codehaus.jackson.JsonParser</tt>). | JSON content is parsed with a ''parser'' (<tt>org.codehaus.jackson.JsonParser</tt>). | ||
<tt>JsonParser</tt> instances are created using factory methods of a <tt>JsonFactory</tt> instance. Once created, they are invoked in a loop, and | <tt>JsonParser</tt> instances are created using factory methods of a <tt>JsonFactory</tt> instance. Once created, they are invoked in a loop, and they identify <tt>JsonToken</tt>s in the input content: | ||
<pre> | |||
while(!parser.isClosed()) { | |||
JsonToken token = parser.nextToken(); | |||
... | |||
} | |||
</pre> | |||
According to the documentation, <tt>nextToken()</tt> is ''the main iteration method'', which will advance stream enough to determine type of the next token, if any. | |||
<tt>JsonToken</tt> is an enumeration, which describe all possible types of tokens identified by the parser. These are: | |||
Revision as of 20:04, 25 February 2017
External
- Parse JSON to Java using Streaming Jackson Parser http://www.studytrails.com/java/json/java-jackson-json-streaming/
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.
JsonToken is an enumeration, which describe all possible types of tokens identified by the parser. These are:
Playground:
Writing Java State as JSON with Streaming API
Java state is written as JSON using a generator (org.codehaus.jackson.JsonGenerator).
Playground: