Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Jackson Streaming API to read and write JSON example

Jackson project has implemented a very useful Streaming API which is also called incremental mode. This is the most efficient way to process JSON content. It has the lowest memory and processing overhead, and can often match performance of many binary data formats available on Java platform. It’s a bit tricky to use though because you have to handle JSON data in all it’s details.

In this example we are going to use JsonGenerator to write a JSON representation to a file and JsonParser to parse a file ton JSON representation.
 
 
 

1. Create a JSON representation and write it to a File

JacksonStreamAPIExample.java:

package com.javacodegeeks.java.core;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;

public class JacksonStreamAPIExample {

	private static final String jsonFilePath = "C:\\Users\\nikos7\\Desktop\\filesForExamples\\jsonFile.json";

	public static void main(String[] args) {

		try {

			JsonFactory jsonfactory = new JsonFactory();

			File jsonFile = new File(jsonFilePath);

			JsonGenerator jsonGenerator = jsonfactory.createJsonGenerator(jsonFile, JsonEncoding.UTF8);

			jsonGenerator.writeStartObject();

			jsonGenerator.writeStringField("domain", "javacodegeeks.com");

			jsonGenerator.writeNumberField("members", 200);

			jsonGenerator.writeFieldName("names");

			jsonGenerator.writeStartArray();

			jsonGenerator.writeString("John");
			jsonGenerator.writeString("Jack");
			jsonGenerator.writeString("James");

			jsonGenerator.writeEndArray();

			jsonGenerator.writeEndObject();

			jsonGenerator.close();

			System.out.println("The file was created successfully");

		} catch (JsonGenerationException e) {

			e.printStackTrace();

		} catch (JsonMappingException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

	}

}

jsonFile.json:

{"domain":"javacodegeeks.com","members":200,"names":["John","Jack","James"]}

2. Parse a JSON file

This is the tricky part in the Streaming API. In this, every single string is considered a token. It’s a classic parsing procedure.

We are going to use jsonFile.json as an input file for the demp.

Let’s see the code:

JacksonStreamAPIExample.java:

package com.javacodegeeks.java.core;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;

public class JacksonStreamAPIExample {

	private static final String jsonFilePath = "C:\\Users\\nikos7\\Desktop\\filesForExamples\\jsonFile.json";

	public static void main(String[] args) {

		try {

			JsonFactory jsonfactory = new JsonFactory();

			//input file
			File jsonFile = new File(jsonFilePath);

			JsonParser jsonParser = jsonfactory.createJsonParser(jsonFile);

			// Begin the parsing procedure 
			while (jsonParser.nextToken() != JsonToken.END_OBJECT) {

				String token = jsonParser.getCurrentName();

				if ("domain".equals(token)) {

					// get the next token which will  be the value...
					jsonParser.nextToken();
					System.out.println("domain : "+jsonParser.getText()); 

				}

				if ("members".equals(token)) {

					jsonParser.nextToken();
					System.out.println("members : " + jsonParser.getIntValue()); 

				}

				if ("names".equals(token)) {

					System.out.println("names :");

					//the next token will be '[' that means that we have an array
					jsonParser.nextToken(); 

					// parse tokens until you find  ']'
					while (jsonParser.nextToken() != JsonToken.END_ARRAY) {

						System.out.println(jsonParser.getText());
					}

				}

			}

			jsonParser.close();

		} catch (JsonGenerationException e) {

			e.printStackTrace();

		} catch (JsonMappingException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}
	}
}

output:

domain : javacodegeeks.com
members : 200
names :
John
Jack
James

 
This was an example on how to use Jackson Streaming API to read and write JSON.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close