Jackson Streaming API – read and write json

In this post,we will see how can we will use jackson streaming API to read and write JSON .

Java JSON Tutorial Content:

In previous post, we have seen jackson example, but it reads whole json file in memory but if we have large json file, then it is not efficient. So If you want to read or write large json file, we need to use jackson streaming API which do not read whole file in memory.
Two important classes for jackson streaming API are:
  • JsonGenerator : To write json
  • JsonParser : To read json
But Jackson streaming API is very less flexible and can not be easily used. We need to handle each and every field and there is no need to create java object unless explicitly required.


In this post,we will read and write JSON using Jackson Streaming API.
1). Create a java project named “JacksonStreamingAPIExample”

2) Add following maven dependency for jackson.
Pom.xml :

 
 4.0.0

 com.arpit.java2blog
 JacksonStreamingAPIExample
 0.0.1-SNAPSHOT
 jar

 JacksonStreamingAPIExample
 http://maven.apache.org

 
 UTF-8
 

 
 
 junit
 junit
 3.8.1
 test
 
 
 org.codehaus.jackson
 jackson-xc
 1.9.13
 
 

3) create a pojo named “Country.java”

package org.arpit.java2blog.pojo;

import java.util.ArrayList;
import java.util.List;

public class Country {

 String name;
 int population;
 private List listOfStates;

 //getter and setter methods

 public String getName() {
      return name;

 public void setName(String name) {
  this.name = name;
 }

 public int getPopulation() {
  return population;
 }

 public void setPopulation(int population) {
  this.population = population;
 }

 public List getListOfStates() {
  return listOfStates;
 }

 public void setListOfStates(List listOfStates) {
 this.listOfStates = listOfStates;
 }

}

Write JSON to file:

4) Create a new class named “JacksonWriteToFileStreamingAPIExample.java” in src->org.arpit.java2blog.JacksonStreamingAPIExample

package com.arpit.java2blog.JacksonStreamingAPIExample;

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

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.util.DefaultPrettyPrinter;

/**
 * 
 * @author Arpit Mandliya
 *
 */
public class JacksonWriteToFileStreamingAPIExample 
{
    public static void main( String[] args )
    {
       try {
     JsonFactory jfactory = new JsonFactory();

     // Write json to a file
     JsonGenerator jsonGenerator = jfactory.createJsonGenerator(new File("//Users//Arpit//countryStreaming.json"), JsonEncoding.UTF8);
     jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
     jsonGenerator.writeStartObject(); // {
     //"name" : "India"
     jsonGenerator.writeStringField("name", "India");
     // "population" : "10000"
     jsonGenerator.writeNumberField("population", 10000);

     // "listOfStates" :
     // This is an array object
     jsonGenerator.writeFieldName("listOfStates");
     // Create start of array tag  [
     jsonGenerator.writeStartArray();

     jsonGenerator.writeString("Madhya Pradesh");

     jsonGenerator.writeString("Maharashtra");

     jsonGenerator.writeString("Rajasthan");
     // Create End of array tag  ]
     jsonGenerator.writeEndArray();
     // end of JSON Object tag }
     jsonGenerator.writeEndObject();

     jsonGenerator.close();

    } catch (JsonGenerationException e) {

     e.printStackTrace();

    } catch (IOException e) {

     e.printStackTrace();

    }
    }
}

Run above program and content of file countryStreaming.json will be as below :

{
  "name" : "India",
  "population" : 10000,
  "listOfStates" : [ "Madhya Pradesh", "Maharashtra", "Rajasthan" ]
}

Read JSON to file:

Here we will read above created JSON file.
5) Create a new class named “JacksonJsonReadFromFileExample.java” in src->org.arpit.java2blog.JacksonStreamingAPIExample

package com.arpit.java2blog.JacksonStreamingAPIExample;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;

public class JacksonStreamingReadFromFileExample {

 public static void main(String[] args)
 {
  try {

   JsonFactory jfactory = new JsonFactory();

   System.out.println("Reading data from json file");
                        System.out.println("--------------------------");
   JsonParser jParser = jfactory
     .createJsonParser(new File("//Users//Arpit//countryStreaming.json"));

   // We need to loop until we reach to the end object.
   while (jParser.nextToken() != JsonToken.END_OBJECT) {

    String fieldname = jParser.getCurrentName();
    if ("name".equals(fieldname)) {

     jParser.nextToken();
     System.out.println("Name of Country:"+jParser.getText());
    }

    if ("population".equals(fieldname)) {
     jParser.nextToken();
     System.out.println("Population: "+jParser.getText());
    }
    // reading the listOfStates which is an array
    if ("listOfStates".equals(fieldname)) {
     // current token is "[" beginning of array. So we wii go to  next
     jParser.nextToken();
     System.out.println("List of states:");
     // iterate through the array until token equal to "]"
     while (jParser.nextToken() != JsonToken.END_ARRAY) {

      System.out.println(jParser.getText());
     }
    }

   }
   jParser.close();

  } catch (JsonGenerationException e) {

   e.printStackTrace();

  } catch (IOException e) {

   e.printStackTrace();

  }
 }
}

Run above program and you will get following output:

Reading data from json file
--------------------------
Name of Country:India
Population: 10000
List of states:
Madhya Pradesh
Maharashtra
Rajasthan
click to begin
20KB .zip

6) Project Structure:

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Comments

    1. You can go to maven central repository – http://search.maven.org/ – and for each of the listed dependencies search for their associated versions. When you find them in the repository there will be a link to allow you to download the jar file manually.

      Once you have them downloaded locally you just set your classpath to their location when you run the program or configure your development environment to look at the location when it builds or launches the app.

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.