How to Read / Write JSON Using Jackson JsonParser and JsonGenerator

In this tutorial, I show you how to create a JSON content using Jackson JsonGenerator class and how to read JSON content using Jackson JsonParser class.
  • 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.

Dependencies

Let’s first add the following dependencies to the pom.xml:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
This dependency will also transitively add the following libraries to the classpath:
  • jackson-annotations-2.9.8.jar
  • jackson-core-2.9.8.jar
  • jackson-databind-2.9.8.jar
Always use the latest versions on the Maven central repository for Jackson databind.

Using JsonGenerator for Writing JSON content

In order to create a Jackson JsonGenerator, we must first create a JsonFactory instance. Here is how we can create a JsonFactory:
JsonFactory factory = new JsonFactory();
Once we have created the JsonFactory then we can create the JsonGenerator using the createGenerator() method of the JsonFactory. Here is an example of creating a JsonGenerator:
JsonFactory factory = new JsonFactory();

JsonGenerator generator = factory.createGenerator(
    new File("post.json"), JsonEncoding.UTF8);
Here is a complete example of writing JSON content to an external file:
package net.javaguides.jackson;

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

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

/**
 * Write JSON from file using JsonGenerator
 * @author Ramesh Fadatare
 *
 */
public class WriteJsonUsingJsonGenerator {

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

        // Create JsonGenerator
        JsonGenerator generator = factory.createGenerator(new File("post.json"), JsonEncoding.UTF8);

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

        // Add string field
        generator.writeNumberField("id", 100);
        generator.writeStringField("title", "Jackson JSON API Guide");
        generator.writeStringField("description", "Post about Jackson JSON API");
        generator.writeStringField("content", "HTML content here");

        // Creating JSON Array within JSON Object
        generator.writeFieldName("tags");

        // Array of Tag objects
        generator.writeStartArray(); // Start with left bracket i.e. [

        // first tag object
        generator.writeStartObject(); // Start with left brace i.e. {
        generator.writeNumberField("id", 1);
        generator.writeStringField("name", "JSON");
        generator.writeEndObject(); // End with right brace i.e }

        // second tag object
        generator.writeStartObject(); // Start with left brace i.e. {
        generator.writeNumberField("id", 2);
        generator.writeStringField("name", "Java");
        generator.writeEndObject(); // End with right brace i.e }

        // second tag object
        generator.writeStartObject(); // Start with left brace i.e. {
        generator.writeNumberField("id", 3);
        generator.writeStringField("name", "Jackson");
        generator.writeEndObject(); // End with right brace i.e }

        generator.writeEndArray(); // End with right bracket i.e. ]

        generator.writeEndObject(); // End with right brace i.e }

        // Close JSON generator
        generator.close();
        // Print JSON Object
    }
}
Let's run above program will write JSON content to "post.json" file. The JSON content looks like

post.json file

{
  "id" : 100,
  "title" : "Jackson JSON API Guide",
  "description" : "Post about Jackson JSON API",
  "content" : "HTML content here",
  "tags" : [ {
    "id" : 1,
    "name" : "JSON"
  }, {
    "id" : 2,
    "name" : "Java"
  }, {
    "id" : 3,
    "name" : "Jackson"
  } ]
}

Using JsonParser for Reading JSON Content

In this example, we will read JSON content from external file "post.json" (In a previuos example, we have written JSON content to this file).
Let's 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. Here is a complete program to read JSON content from an external file:
package net.javaguides.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;

/**
 * Read JSON from file using JsonParser
 * @author Ramesh Fadatare
 *
 */
public class ReadJsonUsingJsonParser {

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

        // Create Reader/InputStream/File
        File file = new File("post.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 && "title".equals(parser.getCurrentName())) {
            token = parser.nextToken();
            if (token == JsonToken.VALUE_STRING) {
                System.out.println("title : " + parser.getText());
            }
        }
        token = parser.nextToken();
        if (token == JsonToken.FIELD_NAME && "description".equals(parser.getCurrentName())) {
            token = parser.nextToken();
            if (token == JsonToken.VALUE_STRING) {
                System.out.println("description : " + parser.getText());
            }
        }

        token = parser.nextToken();
        if (token == JsonToken.FIELD_NAME && "content".equals(parser.getCurrentName())) {
            token = parser.nextToken();
            if (token == JsonToken.VALUE_STRING) {
                System.out.println("content : " + parser.getText());
            }
        }

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

            System.out.println("Post tags 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.println(parser.getText());
                }
            }
            System.out.println();
        }
        parser.close();
    }
}
Output:
title : Jackson JSON API Guide
description : Post about Jackson JSON API
content : HTML content here
Post tags are - 
JSON
Java
Jackson

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments