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:

    JSON Introduction JSON.simple example-read and write JSON GSON example-read and write JSON Jackson example – read and write JSON Jackson Streaming API - read and write JSON
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 :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.arpit.java2blog</groupId>
 <artifactId>JacksonStreamingAPIExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>JacksonStreamingAPIExample</name>
 <url>http://maven.apache.org</url>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>

 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-xc</artifactId>
   <version>1.9.13</version>
  </dependency>
 </dependencies>
</project>

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<String> 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<String> getListOfStates() {
  return listOfStates;
 }

 public void setListOfStates(List<String> 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: 



Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012