Close

Java JSON processing - Streaming API

[Last Updated: Feb 15, 2016]

The Streaming API javax.json.stream is similar to StAX. But instead of XML it is meant to process large amounts of JSON data efficiently. This is is a low-level API. This API can be divided into two main parts in terms of parsing JSON from external/input source and generating JSON to an output source in a streaming manner. Followings things you have to know to use this API.

  1. The interface javax.json.stream.JsonGenerator is used to generate JSON tree from the application code and to send the generated JSON data to a output stream. This interface has bunch of write methods to write JSON objects and arrays. The instance of this interface can be created by calling javax.json.Json#createGenerator
  2. The interface javax.json.stream.JsonParser is used to read JSON data from an input stream. Though this interface doesn't override java.util.Iterator but it defines hasNext() and next() methods to iterate through javax.json.stream.JsonParser.Event. To read JSON keys/values we use JsonParser#getString() method. The instance of this interface can be created by calling javax.json.Json#createParser

Streaming API example

The following example generates and writes JSON large data to a java.io.PippedOutputStream. At the same time another thread reads from the pipe by using java.io.PipedInputStream and reads JSON data. I used org.fluttercode.datafactory to generate test data in the writer part.


Example Project

Dependencies and Technologies Used:

  • JSR 353 (JSON Processing) API 1.0: API module of JSR 353:Java API for Processing JSON.
  • JSR 353 (JSON Processing) Default Provider 1.0.4: Default provider for JSR 353:Java API for Processing JSON.
  • DataFactory 0.8: Library to generate data for testing.
  • JDK 1.8
  • Maven 3.0.4

Steaming Example Select All Download
  • json-streaming-example
    • src
      • main
        • java
          • com
            • logicbig
              • examples
                • json
                  • streaming
                    • StreamExampleApp.java

    Streaming API Quick view

    See Also