Jackson API - Streaming parser and generator example

Posted on March 17, 2018


Jackson API is one of the most popular and powerful JSON java library. It provides core low-level streaming parser and generator for reading and writing JSON content respectively.

JsonParser - It is the base class of Jackson API for reading JSON content.

JsonGenerator - It is the base class of Jackson API for writing JSON content.

The following examples demonstrate how to use the JsonParser and JsonGenerator in java program.

JAR dependencies

Add the following jar dependency to your classpath.

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
   <version>2.9.3</version>
</dependency>

Using JsonGenerator for Writing JSON content

To write JSON content to a file or stream -

First, Retrieve the JsonGenerator object from JsonFactory class.

Then use the writeXXX() methods of the JsonGenerator class to write JSON objects.

JacksonGeneratorExample.java

package com.boraji.tutorial.jackson;

import java.io.IOException;
import java.io.StringWriter;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;

public class JacksonGeneratorExample {
   public static void main(String[] args) throws IOException {
      JsonFactory factory = new JsonFactory();

      // Create Writer/OutputStream/File 
      StringWriter jsonObjectWriter = new StringWriter();

      // Create JsonGenerator
      JsonGenerator generator = factory.createGenerator(jsonObjectWriter);

      //Creating JSON Oject
      generator.writeStartObject(); // Start with left brace i.e. {

      // Add string field
      generator.writeStringField("id", "54348");
      generator.writeStringField("name", "Sunil Singh");
      generator.writeNumberField("age", 30);

      // Creating JSON Array within JSON Object
      generator.writeFieldName("skills");
      generator.writeStartArray();   // Start with left bracket i.e. [
      //Add array's values
      generator.writeString("Java");
      generator.writeString("Spring");
      generator.writeString("Hibernate");
      generator.writeString("SQL");
      generator.writeEndArray();    // End with right bracket i.e. ]
      
      //Creating JSON Object within JSON Object
      generator.writeFieldName("address");
      generator.writeStartObject();
      generator.writeStringField("city", "Jaipur");
      generator.writeStringField("country", "India");
      generator.writeEndObject();
      generator.writeEndObject(); // End with right brace i.e }

      //Close JSON generator
      generator.close();
      // Print JSON Object
      System.out.println(jsonObjectWriter.toString());

   }
}

Output of this program will look like as follows-

{
	"id": "54348",
	"name": "Sunil Singh",
	"age": 30,
	"skills": [
		"Java",
		"Spring",
		"Hibernate",
		"SQL"
	],
	"address": {
		"city": "Jaipur",
		"country": "India"
	}
}

 

Using JsonParser for reading JSON content

To Read JSON content from a file or stream -

First, Retrieve the JsonParser object from JsonFactory class.

Then use the JsonToken to iterate the returning result of parsing JSON content.

The following example parses the JSON content generated by the above example.

JacksonParserExample.java

package com.boraji.tutorial.jackson;

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

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

public class JacksonParserExample {
   public static void main(String[] args) throws IOException {
      JsonFactory factory = new JsonFactory();

      // Create Reader/InputStream/File
      File file = new File("myfile.json");

      // Create JsonParser
      JsonParser parser = factory.createParser(file);

      JsonToken token = parser.nextToken(); // Read first object i.e. {

      // Read JSON object
      token = parser.nextToken();
      if (token == JsonToken.FIELD_NAME && "id".equals(parser.getCurrentName())) {
         token = parser.nextToken();
         if (token == JsonToken.VALUE_STRING) {
            System.out.println("ID : " + parser.getText());
         }
      }
      token = parser.nextToken();
      if (token == JsonToken.FIELD_NAME && "name".equals(parser.getCurrentName())) {
         token = parser.nextToken();
         if (token == JsonToken.VALUE_STRING) {
            System.out.println("NAME : " + parser.getText());
         }
      }
      token = parser.nextToken();
      if (token == JsonToken.FIELD_NAME && "age".equals(parser.getCurrentName())) {
         token = parser.nextToken();
         if (token == JsonToken.VALUE_NUMBER_INT) {
            System.out.println("AGE : " + parser.getIntValue());
         }
      }

      // Reading JSON Array
      token = parser.nextToken();
      if (token == JsonToken.FIELD_NAME && "skills".equals(parser.getCurrentName())) {

         System.out.println("\nYour skills are - ");
         token = parser.nextToken(); // // Read left bracket i.e. [
         // Loop to print array elements until right bracket i.e ]
         while (token != JsonToken.END_ARRAY) {
            token = parser.nextToken();

            if (token == JsonToken.VALUE_STRING) {
               System.out.print(parser.getText() + ", ");
            }
         }
         System.out.println();
      }

      // Reading nested JSON Object
      token = parser.nextToken();
      if (token == JsonToken.FIELD_NAME && "address".equals(parser.getCurrentName())) {

         token = parser.nextToken(); // Read first object i.e. {
         
         System.out.println("\nYour Address is - ");
         token = parser.nextToken();
         if (token == JsonToken.FIELD_NAME && "city".equals(parser.getCurrentName())) {
            token = parser.nextToken();
            if (token == JsonToken.VALUE_STRING) {
               System.out.println("CITY : " + parser.getText());
            }
         }
         token = parser.nextToken();
         if (token == JsonToken.FIELD_NAME && "country".equals(parser.getCurrentName())) {
            token = parser.nextToken();
            if (token == JsonToken.VALUE_STRING) {
               System.out.println("COUNTRY : " + parser.getText());
            }
         }

      }
      parser.close();
   }
}

Output of your program will look like as following -

ID : 54348
NAME : Sunil Singh
AGE : 30

Your skills are - 
Java, Spring, Hibernate, SQL, 

Your Address is - 
CITY : Jaipur
COUNTRY : India