Resolves the use of the Streaming API in Java's Jackson library

  • 2020-04-01 04:36:07
  • OfStack

The streaming API reads and writes JSON content discrete events. The JsonParser reads the data, while the JsonGenerator writes the data. It is the most efficient of the three, with the lowest overhead and the fastest read/write operation. It is similar to the Stax parser for XML.

In this article, we'll show you how to read and write JSON data using Jackson's streaming API. Streaming API work using JSON for every detail is handled with care. The following example USES two classes:
JsonGenerator class -- writes a JSON string.
SonGenerator is the base class that defines the Json content written by the public API. Create an instance using the factory method of the JsonFactory instance.

Class declaration
Below is the org. Codehaus. Jackson. JsonGenerator class declaration:


public abstract class JsonGenerator
  extends Object
   implements Closeable

Nested classes

S.N. Class and instructions
1 static class JsonGenerator.Feature// Enumeration defines all of the generator togglable Function.

field
Protected PrettyPrinter _cfgPrettyPrinter - object that handles fairly printed (usually redundant white space to make the result more readable) output.

The constructor

S.N. Class and instructions
1 Default constructor

JsonParser class -- parses JSON strings.
JsonParser is the base class that defines the Json content that the public API USES to read. Create an instance using the factory method of the JsonFactory instance.

Class declaration
The following is a org. Codehaus. Jackson. JsonParser class declaration:


public abstract class JsonParser
  extends Object
   implements Closeable, Versioned

Nested classes

S.N. Class and instructions
1 static class JsonParser.Feature // Enumeration defines all of the parsers togglable Function.
2 static class JsonParser.NumberType // Enumeration can be used for the possible "local" of Numbers ( The best ) Type.

field

Protected PrettyPrinter _cfgPrettyPrinter - the object handles rather printed (usually redundant white space to make the result more readable) output. Protected JsonToken _currToken - retrieves the last token, if any, through nextToken(). Protected int _features - bit flag bit to indicate that it has jsonparser.features composition enabled. Protected JsonToken _lastClearedToken - finally clears the token if there is one: clearCurrentToken() is called when the value is valid.

The constructor

S.N. Class and instructions
1 protected JsonParser() // The default constructor
2 protected JsonParser(int features)

Inherited method
This class inherits the following class methods:


java.lang.Object

Write JSON using the JsonGenerator
Using JsonGenerator is very simple. First use JsonFactory. CreateJsonGenerator () method to create a JsonGenerator, and write * * * () method to write each JSON values.


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's look at the JsonGenerator operation. Create a Java class file named JacksonTester in the directory 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();
   }
  }
}

The verification results

Compile the following classes using javac:


C:Jackson_WORKSPACE>javac JacksonTester.java

Now run jacksonTester and see the results:


C:Jackson_WORKSPACE>java JacksonTester


Verify the output


Mahesh Kumar
21
false
[100, 90, 85]

JSON is read using JsonParser
Using JsonParser is very simple. First use JsonFactory. CreateJsonParser () method to create JsonParser, and use its nextToken () method to read each JSON string as a tag. Examine each token and the corresponding procedure.


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's look at the JsonParser in action. Create a Java class named JacksonTester in folder 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();
   }
  }
}

The verification results

Compile the following classes using javac:

The same code at the page code block index 1
Now run jacksonTester and see the results as follows:

The same code at the page code block index 2
Verify the output


Mahesh Kumar
21
false
[100, 90, 85]


Related articles: