Jackson - Streaming API


Advertisements


Streaming API reads and writes JSON content as discrete events. JsonParser reads the data, whereas JsonGenerator writes the data.

  • It is the most powerful approach among the three processing modes that Jackson supports.

  • It has the lowest overhead and it provides the fastest way to perform read/write operations.

  • It is analogous to Stax parser for XML.

In this chapter, we will discuss how to read and write JSON data using Jackson streaming APIs. Streaming API works with the concept of token and every details of JSON is to be handled carefully. Following are the two classes which we will use in the examples given in this chapter −

Write to JSON using JsonGenerator

It is pretty simple to use JsonGenerator. First, create the JsonGenerator using JsonFactory.createJsonGenerator() method and use its write***() methods to write each JSON value.

JsonFactory jasonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jasonFactory.createJsonGenerator(new File("student.json"),
   JsonEncoding.UTF8);

jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"

jsonGenerator.writeStringField("name", "Mahesh Kumar"); 

Let us see JsonGenerator in action. Create a Java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

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

import java.util.Map;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;

import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) {
   
      JacksonTester tester = new JacksonTester();
		
      try {        	
         JsonFactory jasonFactory = new JsonFactory();

         JsonGenerator jsonGenerator = jasonFactory.createJsonGenerator(new File("student.json"),
            JsonEncoding.UTF8); // {
            jsonGenerator.writeStartObject();
					
            // "name" : "Mahesh Kumar"
            jsonGenerator.writeStringField("name", "Mahesh Kumar"); 
				
            // "age" : 21
            jsonGenerator.writeNumberField("age", 21);
				
            // "verified" : false
            jsonGenerator.writeBooleanField("verified", false);
				
            // "marks" : [100, 90, 85]
            jsonGenerator.writeFieldName("marks"); 
				
            // [
               jsonGenerator.writeStartArray(); 
               // 100, 90, 85
               jsonGenerator.writeNumber(100); 
               jsonGenerator.writeNumber(90); 
               jsonGenerator.writeNumber(85); 
            // ]
				
            jsonGenerator.writeEndArray(); 
				
         // }
			
         jsonGenerator.writeEndObject(); 
         jsonGenerator.close();       	 

         //result student.json
         //{ 
         //   "name":"Mahesh Kumar",
         //   "age":21,
         //   "verified":false,
         //   "marks":[100,90,85]
         //}
			
         ObjectMapper mapper = new ObjectMapper();
         Map<String,Object> dataMap = mapper.readValue(new File("student.json"), Map.class);

         System.out.println(dataMap.get("name"));
         System.out.println(dataMap.get("age"));
         System.out.println(dataMap.get("verified"));
         System.out.println(dataMap.get("marks"));
			
      } catch (JsonParseException e) { 
         e.printStackTrace();
      } catch (JsonMappingException e) { 
         e.printStackTrace(); 
      } catch (IOException e) { 
         e.printStackTrace(); 
      }
   }
}

Verify the Result

Compile the classes using javac compiler as follows −

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now execute the jacksonTester to see the result.

C:\Jackson_WORKSPACE>java JacksonTester

Verify the output −

Mahesh Kumar
21
false
[100, 90, 85]

Reading JSON using JsonParser

Using JsonParser is again pretty simple. First, create the JsonParser using JsonFactory.createJsonParser() method and use its nextToken() method to read each JSON string as token. Check each token and process accordingly.

JsonFactory jasonFactory = new JsonFactory();
JJsonParser jsonParser = jasonFactory.createJsonParser(new File("student.json"));

while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
   
   //get the current token
   String fieldname = jsonParser.getCurrentName();
	
   if ("name".equals(fieldname)) {
      
      //move to next token
      jsonParser.nextToken();
      System.out.println(jsonParser.getText());        	 
   }
}

Let us see JsonParser in action. Create a Java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

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;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;

public class JacksonTester {
   public static void main(String args[]) {
      JacksonTester tester = new JacksonTester();
      
      try {        	
         JsonFactory jasonFactory = new JsonFactory();

         JsonGenerator jsonGenerator = jasonFactory.createJsonGenerator(new File("student.json"),
            JsonEncoding.UTF8);
         jsonGenerator.writeStartObject();
         jsonGenerator.writeStringField("name", "Mahesh Kumar"); 
         jsonGenerator.writeNumberField("age", 21);
			
         jsonGenerator.writeBooleanField("verified", false); 
         jsonGenerator.writeFieldName("marks"); 
			
         jsonGenerator.writeStartArray(); // [
			
         jsonGenerator.writeNumber(100); 
         jsonGenerator.writeNumber(90); 
         jsonGenerator.writeNumber(85); 
			
         jsonGenerator.writeEndArray(); 
         jsonGenerator.writeEndObject(); 

         jsonGenerator.close();       	 

         //result student.json
			
         //{ 
            //   "name":"Mahesh Kumar",
            //   "age":21,
            //   "verified":false,
            //   "marks":[100,90,85]
         //}

         JsonParser jsonParser = jasonFactory.createJsonParser(new File("student.json"));
			
         while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
            //get the current token
            String fieldname = jsonParser.getCurrentName();
				
            if ("name".equals(fieldname)) {
               //move to next token
               jsonParser.nextToken();
               System.out.println(jsonParser.getText());        	 
            }
				
            if("age".equals(fieldname)) {
               //move to next token
               jsonParser.nextToken();
               System.out.println(jsonParser.getNumberValue());        	 
            }
				
            if("verified".equals(fieldname)) {
               //move to next token
               jsonParser.nextToken();
               System.out.println(jsonParser.getBooleanValue());        	 
            }
				
            if("marks".equals(fieldname)) {
               //move to [ 
               jsonParser.nextToken();
               // loop till token equal to "]"
					
               while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                  System.out.println(jsonParser.getNumberValue()); 
               }
            }
         }
      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Verify the Result

Compile the classes using javac compiler as follows −

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result.

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output −

Mahesh Kumar
21
false
[100, 90, 85]


Advertisements