পৃষ্ঠাসমূহ

Search Your Article

CS

 

Welcome to GoogleDG – your one-stop destination for free learning resources, guides, and digital tools.

At GoogleDG, we believe that knowledge should be accessible to everyone. Our mission is to provide readers with valuable ebooks, tutorials, and tech-related content that makes learning easier, faster, and more enjoyable.

What We Offer:

  • 📘 Free & Helpful Ebooks – covering education, technology, self-development, and more.

  • 💻 Step-by-Step Tutorials – practical guides on digital tools, apps, and software.

  • 🌐 Tech Updates & Tips – simplified information to keep you informed in the fast-changing digital world.

  • 🎯 Learning Support – resources designed to support students, professionals, and lifelong learners.

    Latest world News 

     

Our Vision

To create a digital knowledge hub where anyone, from beginners to advanced learners, can find trustworthy resources and grow their skills.

Why Choose Us?

✔ Simple explanations of complex topics
✔ 100% free access to resources
✔ Regularly updated content
✔ A community that values knowledge sharing

We are continuously working to expand our content library and provide readers with the most useful and relevant digital learning materials.

📩 If you’d like to connect, share feedback, or suggest topics, feel free to reach us through the Contact page.

Pageviews

Tuesday, January 17, 2017

Jackson - Streaming API

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]

No comments:

Post a Comment