Monday, February 25, 2019

Jackson - Streaming API

Streaming API reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML.
In this Article, we'll showcase using Jackson streaming APIs to read and write JSON data. Streaming API works with concept of token and every details of Json is to be handle carefuly. Following are two class which we'll use in the examples:

Writing JSON using JsonGenerator

Using JsonGenerator is pretty simple. First create the JsonGenerator using JsonFactory.createJsonGenerator() method and use it's write***() methods to write each json value.
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(
   "student.json"), JsonEncoding.UTF8);
// {
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField("name", "Mahesh Kumar"); 
Let's 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 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;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){

      try {         
         JsonFactory jsonFactory = new JsonFactory();
         JsonGenerator jsonGenerator = jsonFactory.createGenerator(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 run 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 it's nextToken() methods to read each json string as token. Check each token and process accordingly
JsonFactory jasonFactory = new JsonFactory();
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());          
   }
}
Let's 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 java.util.Map;

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;
import com.fasterxml.jackson.databind.ObjectMapper;

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

         JsonGenerator jsonGenerator = jsonFactory.createGenerator(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 = jsonFactory.createParser(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]

No comments:

Post a Comment

Popular Posts