Jackson Streaming API to read and write JSON

Jackson supports read and write JSON via high-performance Jackson Streaming APIs, or incremental mode. Read this Jackson Streaming APIs document for detail explanation on the benefit of using streaming API.

Jackson’s streaming processing is high-performance, fast and convenient, but it’s also difficult to use, because you need to handle each and every detail of JSON data.

In this tutorial, we show you how to use following Jackson streaming APIs to read and write JSON data.

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

1. JsonGenerator

In this example, you use “JsonGenerator” to write JSON “field name”, “values” and “array of values” into a file name “file.json“. See code comments for self-explanatory.


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 JacksonStreamExample {
   public static void main(String[] args) {

     try {

	JsonFactory jfactory = new JsonFactory();

	/*** write to file ***/
	JsonGenerator jGenerator = jfactory.createJsonGenerator(new File(
			"c:\\user.json"), JsonEncoding.UTF8);
	jGenerator.writeStartObject(); // {

	jGenerator.writeStringField("name", "mkyong"); // "name" : "mkyong"
	jGenerator.writeNumberField("age", 29); // "age" : 29

	jGenerator.writeFieldName("messages"); // "messages" :
	jGenerator.writeStartArray(); // [

	jGenerator.writeString("msg 1"); // "msg 1"
	jGenerator.writeString("msg 2"); // "msg 2"
	jGenerator.writeString("msg 3"); // "msg 3"

	jGenerator.writeEndArray(); // ]

	jGenerator.writeEndObject(); // }

	jGenerator.close();

     } catch (JsonGenerationException e) {

	e.printStackTrace();

     } catch (JsonMappingException e) {

	e.printStackTrace();

     } catch (IOException e) {

	e.printStackTrace();

     }

   }

}

As result, following new file named “file.json” is created :


{
	"name":"mkyong",
	"age":29,
	"messages":["msg 1","msg 2","msg 3"]
}

2. JsonParser

On the other hand, use JsonParser to parse or read above file “file.json“, and display each of the values.

Token concept
In streaming mode, every JSON “string” is consider as a single token, and each tokens will be processed incremental, that why we call it “incremental mode”. For example,


{
   "name":"mkyong"
}
  1. Token 1 = “{“
  2. Token 2 = “name”
  3. Token 3 = “mkyong”
  4. Token 4 = “}”

See full example.


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 JacksonStreamExample {
   public static void main(String[] args) {

     try {

	JsonFactory jfactory = new JsonFactory();

	/*** read from file ***/
	JsonParser jParser = jfactory.createJsonParser(new File("c:\\user.json"));

	// loop until token equal to "}"
	while (jParser.nextToken() != JsonToken.END_OBJECT) {

		String fieldname = jParser.getCurrentName();
		if ("name".equals(fieldname)) {

		  // current token is "name",
                  // move to next, which is "name"'s value
		  jParser.nextToken();
		  System.out.println(jParser.getText()); // display mkyong

		}

		if ("age".equals(fieldname)) {

		  // current token is "age", 
                  // move to next, which is "name"'s value
		  jParser.nextToken();
		  System.out.println(jParser.getIntValue()); // display 29

		}

		if ("messages".equals(fieldname)) {

		  jParser.nextToken(); // current token is "[", move next

		  // messages is array, loop until token equal to "]"
		  while (jParser.nextToken() != JsonToken.END_ARRAY) {

                     // display msg1, msg2, msg3
		     System.out.println(jParser.getText()); 

		  }

		}

	  }
	  jParser.close();

     } catch (JsonGenerationException e) {

	  e.printStackTrace();

     } catch (JsonMappingException e) {

	  e.printStackTrace();

     } catch (IOException e) {

	  e.printStackTrace();

     }

  }

}
Warning
The array parsing is a bit tricky, read code comments for explanation.

Output


mkyong
29
msg 1
msg 2
msg 3

Conclusion

In summary, for performance critical application, use Steaming API, otherwise, just use normal Jackson data binding.

References

  1. Jackson Streaming API documentation
  2. Jackson Streaming API short example
  3. Gson Streaming example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
James Blant
Guest
James Blant

Hi, the above example reads only one object. Please help me with how to read more than one object.

thanx in advance.

James Blant
Guest
James Blant

Hi, your tutorials are always helpful.I need some help about how I can append json objects in the file instead of overwriting it.Thanx

Behrooz Amirinejad
Guest
Behrooz Amirinejad
i`m developing an android application that wanna send a file over internet to restful server but gets fault on writeBinary(File , -1); ; this is my full code : public void UploadFile(org.apache.commons.codec.binary.Base64InputStream File) throws Exception { try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(“Content-Type”, “application/cdmi-object”); conn.setRequestMethod(“PUT”); conn.setDoInput(true); conn.setDoOutput(true); int buffSize = 5000; conn.setChunkedStreamingMode(buffSize); OutputStream os = conn.getOutputStream(); JsonFactory jfactory = new JsonFactory(); JsonGenerator jGenerator = jfactory.createGenerator(os); jGenerator.writeStartObject(); // { jGenerator.writeFieldName(“metadata”); jGenerator.writeStartObject(); // metadata:{ jGenerator.writeStringField(“fromClient”, “true”); jGenerator.writeEndObject();// metadata:} jGenerator.writeStringField(“valuetransferencoding”, “base64”); jGenerator.writeFieldName(“value”); jGenerator.writeBinary(File , -1); jGenerator.writeEndObject(); // } jGenerator.close(); int resultCode = conn.getResponseCode(); if (resultCode != HttpURLConnection.HTTP_OK) { } else { conn.disconnect();… Read more »
San
Guest
San

instead of a file is there a way to generate it to String? I dont want to write to a file, instead wanted to create a string object which I can use to post to rest.

Raj
Guest
Raj

How to parse the following JSON string?
{“Response”:{“AuthenticateResponse”:{“status”:{“message”:”Authentication Sucessful”,”code”:”0.0″},”data”:{“assetid”:[“AP09Y6984″,”BR01G6028″,”CG04CW6399″,”JH05AH6102″,”NL01G7946″,”PB10CA2017″,”TN21AF6814″,”UK06CA1435″,”WB615937″,”WB67A0482″]},”auth”:{“id”:”f6b2797a747986f39b16c4c5ce27c5a8″}}}}

Please help me.

Lenin
Guest
Lenin

How to parse the following text? retweeted_status is not an array. It is another json object.

“retweeted_status”:{
“contributors”:null
,”text”:”Sample text”
,”geo”:null,
“retweeted”:false
}

Striker
Guest
Striker

How to write the same json in an JSON Object?

Jeff
Guest
Jeff

Nice!

Question: If every json string is consider token:

{
“name”:”mkyong”
}
became:
Token 1 = “{“
Token 2 = “name”
Token 3 = “mkyong”
Token 4 = “}”

Why “:” is not consider token?

Lenin
Guest
Lenin

Maybe because it treats “:” as a delimiter for key and value

trackback
Gson Streaming to read and write JSON

[…]   }   }Outputmkyong 29 msg 1 msg 2 msg 3ReferencesGson streaming documentationJackson streaming example […]