Read and Write JSON – Jackson Streaming API

2 Flares Twitter 0 Facebook 1 Google+ 1 LinkedIn 0 2 Flares ×

This is the second post in the Java JSON tutorial series and here we will explore the Streaming API of the popular Jackson JSON Library. The first post was using the ObjectMapper of  Jackson Library and you can read it here.

Streaming Processing (also known as Incremental Processing) is the most efficient way to process JSON content.It offers lowest memory footprint, less processing overhead and in most cases can give performance matching the binary data formats. But keep in mind that when you for extreme performance there is always a risk of loosing flexibility and ease of use. The case is no different here. There is a cost to pay for the high performance

  1. All content to read/write has to be processed in exact same order as input comes in (or output is to go out)
  2. There is no random access and if you need random access use Data Binding or Tree Model
  3. No Java objects are created unless specifically requested; and even then only very basic types are supported (Strings, byte[] for base64-encoded binary content)

Due to the less flexibility Streaming API is typically used by middle-ware and frameworks and less often by applications. Of course  if your application has very high performance requirements you can always use the Streaming API. Encourage you to read more about the Jackson Streaming API 

The important classes are

  1. JsonGenerator – To Write JSON.
  2. JsonParser – To Parse JSON.

Write JSon Data – JsonGenerator

In this example we will see how we can use the JsonGenerator to generate JSON data. Generators are objects used to construct JSON content based on sequence of calls to output JSON tokens.Most common way to create generators is to pass an external destination (File) into which to write resulting JSON content.

Please note that for the examples below we are using the Latest stable 2.x version of Jackson library.


Now let us see how we can read the JSON data from a file using the JSON parser. For this example let us use the same data.json file we create in the above example. Since this is a streaming API it just streams the data on the fly. We need to loop from the beginning of the JSON data till the end and we need to compare the currently processing field name against the one we are interested in to read the data. That’s why we said Streaming API is less flexible. But for performance there is nothing better.

Read JSON – JsonParser Example


Final Thoughts

For normal applications use Jackson Data Binding API and if your application’s  most important goal is performance use the Streaming API. In most cases the Data Binding API is a good choice.


Jackson Streaming API Wiki

Download Jackson Library