Jackson reads and writes JSON through a high-performance Jackson Streaming API, with a low memory and process overhead. The only problem with Streaming API is that we need to take care of all the tokens while parsing JSON data. All the JSON values must be read/write in the same order in which it arrives.
Let’s take an example if we have a JSON string as
{“Name”:”JavaInterviewPoint”}
then we will be getting the tokens in the below order.
- { –>start of JSON
- Name –> Key
- JavaInterviewPoint –> Value
- } –> End of JSON
Due to this complexity in nature, Jackson Streaming API is generally used in frameworks internally.
Folder Structure:
-
- Create a new Java Project “JacksonJSONTutorial” and create a package for our src files “com.javainterviewpoint“
- Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.
jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar
if you are running on maven add the below dependency to your pom.xml
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
- Create the Java classes Jackson_Streaming_Read_Example.java and Jackson_Streaming_Write_Example.java under com.javainterviewpoint folder.
Jackson Streaming API Example
In this tutorial, we will learn how to use following Jackson streaming API to read and write JSON data.
- JsonGenerator – Write Java String to JSON
- JsonParser – Parse JSON to Java.
Convert Java to JSON Using Jackson JsonParser
package com.javainterviewpoint; import java.io.File; import java.io.IOException; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; public class Jackson_Streaming_Read_Example { public static void main(String args[]) { try { //Create a JsonFactory JsonFactory factory = new JsonFactory(); //JsonParser for reading the JSON File JsonParser parser = factory. createJsonParser(new File("C:\\user.json")); //Pointing to the first token parser.nextToken(); while(parser.nextToken()!= JsonToken.END_OBJECT) { //Getting the token name String key = parser.getCurrentName(); if(key.equals("Name")) { /**Here current token is "Name" * nextToken() will point to the next token, * which will be Name's value */ parser.nextToken(); System.out.println(key+" : "+parser.getText()); } if(key.equals("Age")) { parser.nextToken(); System.out.println(key+" : "+parser.getText()); } if(key.equals("Countries")) { parser.nextToken(); System.out.println(key); while(parser.nextToken()!=JsonToken.END_ARRAY) { System.out.println("\t"+parser.getText()); } } } } catch (JsonParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
- Create a JsonFactory, from which we will be getting JsonParser
JsonFactory factory = new JsonFactory();
- The createJsonParser() method of the factory returns the JsonParser object, we need to pass the input file which you want to read. Here it is “User.json”.
JsonParser parser = factory. createJsonParser(new File("C:\\user.json"));
- nextToken() method will point to the next token, we need to loop it till END_OBJECT (“}”).
- getCurrentName() method will return you the token name, check it with each field of the JSON
String key = parser.getCurrentName(); if(key.equals("Name"))
- To get the value of the current token, we use parser.getText() method
System.out.println(key+" : "+parser.getText());
Output :
Convert JSON to Java object using Jackson JsonGenerator
package com.javainterviewpoint; import java.io.File; import java.io.IOException; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonParseException; public class Jackson_Streaming_Write_Example { public static void main(String args[]) { try { //Create a JsonFactory JsonFactory factory = new JsonFactory(); //JsonGenerator for writing the JSON File JsonGenerator generator = factory. createJsonGenerator(new File("C:\\user.json"), JsonEncoding.UTF8); //Writing a JSON opening brace { generator.writeStartObject(); //Writing String key and String value - "Name":"JIP" generator.writeStringField("Name","JIP"); //Writing String key and Integer value - "Age":111 generator.writeNumberField("Age",111); generator.writeFieldName("FavouriteSports"); //Writing a JSON array opening brace [ generator.writeStartArray(); //Writing array value generator.writeString("Football"); generator.writeString("Cricket"); generator.writeString("Chess"); generator.writeString("Baseball"); //Writing a JSON array closing brace ] generator.writeEndArray(); //Writing a JSON closing brace } generator.writeEndObject(); generator.close(); } catch (JsonParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
- Create a JsonFactory, from which we will be getting JsonGenerator
JsonFactory factory = new JsonFactory();
- The createJsonGenerator() method of the factory returns the JsonGenertor object, we need to pass the input file which you want to read and encoding.
JsonGenerator generator = factory. createJsonGenerator(new File("C:\\user.json"), JsonEncoding.UTF8);
- Now let us start writing the JSON using JsonGenerator, we need to write each and every token
- generator.writeStartObject() –> Write the starting brace “{“
- generator.writeStringField(“Name”,”JIP”) –> Write String key(Name) and String value(JIP)
- generator.writeNumberField(“Age”,111) –> Writing String key(Age) and Integer value(111)
- generator.writeFieldName(“FavouriteSports”) –> Writing String key alone(FavouriteSports)
- generator.writeStartArray() –> Writing open brace of the array “[“
- generator.writeString(“Football”) –> Writing the values of the array (Football, Cricket,Chess,Baseball).
- generator.writeEndArray() –> Writing the end brace of the array “]”
- generator.writeEndObject() –> Write the end brace “}”
- Finally close the generator Object using the close() method
generator.close();
Output :
In the user.json file we will be having the below content
{"Name":"JIP","Age":111,"FavouriteSports":["Football","Cricket","Chess","Baseball"]}
Leave a Reply