Jackson Streaming Api Example

For situations where performance is most critical, Jackson comes with Streaming API which is a high performance, sequential access api, with very low memory and processing overhead.

Due to it’s incremental processing/sequential access nature, all content must be read/write in order as it arrives, so it’s bit hard to use. This API is mainly used by middleware and frameworks internally. On application level, to remain simple, usually data-binding or tree-model api’s are preferred(which infact uses the Streaming API internally for JSON reading/writing).

On reading front, API comes with Parsers which works like a pointer moving through individual tokens in JSON string and provide access to data of those tokens.
key, value, brackets [ { } ] are all tokens.

On writing front, Generators are available which writes JSON content. They provide methods to write individual tokens.

Let’s see how it is used exactly:

Step 1: Include JACKSON dependency in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.websystique.xml</groupId>
  <artifactId>JsonJacksonStreamingExample</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <name>JsonJacksonStreamingExample</name>

  <dependencies>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.5.3</version>
	</dependency>
  </dependencies>
 </project>

Step 2: Write JSON using JsonGenerator

package com.websystique.json.jackson;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

public class JsonJacksonStreamingExample {

	public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException{

		JsonFactory factory = new JsonFactory();

		/**
		 * Write values in JSON format to a file
		 */
		JsonGenerator generator = factory.createGenerator(new File("result.json"), JsonEncoding.UTF8);

		generator.writeStartObject();					// write opening brace "{"

		generator.writeStringField("car", "Bentley");	//write key:value pair 		"car":"bentley"
		generator.writeNumberField("model", 2010);	
		generator.writeNumberField("price", 98.700);	

		generator.writeFieldName("colors");				
			
		generator.writeStartArray();					//write array opening brace "["
		
		generator.writeString("gray");					//write individual array item
		generator.writeString("white");
		generator.writeString("black");
	
		generator.writeEndArray();						//write array closing brace "]"
		generator.writeEndObject();						// write closing brace "}"
		generator.close();
		
	}
}

Below is the output(result.json content)

{"car":"Bentley","model":2010,"price":98.7,"colors":["gray","white","black"]}

Step 3: Read JSON using JsonParser

package com.websystique.json.jackson;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;

public class JsonJacksonStreamingExample {

	public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException{
		JsonFactory factory = new JsonFactory();
		/**
		 * Read values in json format
		 */
		JsonParser parser = factory.createParser(new File("result.json"));
		parser.nextToken();										//start reading the file
		while (parser.nextToken() != JsonToken.END_OBJECT) {	//loop until "}"
			   
			   String fieldName = parser.getCurrentName();
			   if (fieldName.equals("car")) {
				   parser.nextToken();
				   System.out.println("car : " + parser.getText());
			   } else if (fieldName.equals("model")) {
				   parser.nextToken();
				   System.out.println("model : " + parser.getIntValue());
			   } else if (fieldName.equals("price")) {
				   parser.nextToken();
				   System.out.println("price : " + parser.getFloatValue());
			   } else if (fieldName.equals("colors")) {
				   parser.nextToken();
				   while (parser.nextToken() != JsonToken.END_ARRAY){	//loop until "]"
					   System.out.println(parser.getText());
				   }
			   } else { // unexpected token, generate error
				   throw new IOException("Unrecognized field '"+fieldName+"'");
			   }
		}
			  parser.close(); 
	}
}

Below is the output

car : Bentley
model : 2010
price : 98.7
gray
white
black

That’s it. In the next post we will learn about frequently used Jackson Json annotations.

References

If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help me improve further our learning process.

If you appreciate the effort I have put in this learning site, help me improve the visibility of this site towards global audience by sharing and linking this site from within and beyond your network. You & your friends can always link my site from your site on www.websystique.com, and share the learning.

After all, we are here to learn together, aren’t we?