• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Jackson Streaming API Example | Read and Write JSON

October 11, 2016 by javainterviewpoint Leave a Comment

Jackson reads and writes JSON through a high-performance Jackson Streaming API, with a low memory and process overhead. The only problem with Streaming API is that we need to take care of all the tokens while parsing JSON data. All the JSON values must be read/write in the same order in which it arrives.

Let’s take an example if we have a JSON string as

{“Name”:”JavaInterviewPoint”}

then we will be getting the tokens in the below order.

  1. { –>start of JSON
  2. Name –> Key
  3. JavaInterviewPoint –> Value
  4. } –>  End of JSON

Due to this complexity in nature, Jackson Streaming API is generally used in frameworks internally.

Folder Structure:

    1. Create a new Java Project  “JacksonJSONTutorial” and create a package for our src files “com.javainterviewpoint“
    2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar

if you are running on maven add the below dependency to your pom.xml

 <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-core-asl</artifactId>
   <version>1.9.13</version>
</dependency>
<dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.13</version>
</dependency>
  1. Create the Java classes Jackson_Streaming_Read_Example.java and Jackson_Streaming_Write_Example.java under  com.javainterviewpoint folder.

Other Posts which you may like …

  • Jackson 2 JSON Parser – Convert JSON to/from Java Object
  • How to Convert JSON to / from Java Map using JACKSON
  • Jackson Tree Model Example – JsonNode
  • Jackson Streaming API Example | Read and Write JSON
  • Jackson JSON Example | ObjectMapper and @JSONView
  • How to Parse JSON to/from Java Object using Boon JSON Parser
  • How to Read and Write JSON using GSON
  • How to write JSON object to File in Java?
  • How to read JSON file in Java – JSONObject and JSONArray
  • Jersey Jackson JSON Tutorial
  • Spring REST Hello World Example – JSON and XML responses
  • How to Convert Java Object to JSON using JAXB
  • JAX-RS REST @Consumes both XML and JSON Example
  • JAX-RS REST @Produces both XML and JSON Example

Jackson Streaming API Example

In this tutorial, we will learn  how to use following Jackson streaming API to read and write JSON data.

  1. JsonGenerator – Write Java String to JSON
  2. JsonParser – Parse JSON to Java.

Convert Java to JSON Using Jackson JsonParser

package com.javainterviewpoint;

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

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;

public class Jackson_Streaming_Read_Example
{
    public static void main(String args[])
    {
        try
        {
            //Create a JsonFactory
            JsonFactory factory = new JsonFactory();
            //JsonParser for reading the JSON File
            JsonParser parser = factory.
                    createJsonParser(new File("C:\\user.json"));
            //Pointing to the first token
            parser.nextToken();  
            while(parser.nextToken()!= JsonToken.END_OBJECT)
            {
                //Getting the token name
                String key = parser.getCurrentName();
                
                if(key.equals("Name"))
                {
                    /**Here current token is "Name"
                     * nextToken() will point to the next token, 
                     * which will be Name's value
                     */
                    parser.nextToken();
                    System.out.println(key+" : "+parser.getText());
                }
                if(key.equals("Age"))
                {
                    parser.nextToken();
                    System.out.println(key+" : "+parser.getText());
                }
                if(key.equals("Countries"))
                {
                    parser.nextToken();
                    System.out.println(key);
                    while(parser.nextToken()!=JsonToken.END_ARRAY)
                    {
                        System.out.println("\t"+parser.getText());
                    }
                }
            }
        } catch (JsonParseException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • Create a JsonFactory, from which we will be getting JsonParser
JsonFactory factory = new JsonFactory();
  • The createJsonParser() method of the factory returns the JsonParser object, we need to pass the input file which you want to read. Here it is “User.json”.
JsonParser parser = factory.
                    createJsonParser(new File("C:\\user.json"));
  • nextToken() method will point to the next token, we need to loop it till END_OBJECT (“}”).
  • getCurrentName() method will return you the token name, check it with each field of the JSON
String key = parser.getCurrentName();
if(key.equals("Name"))
  • To get the value of the current token, we use parser.getText() method
System.out.println(key+" : "+parser.getText());

Output :

Jackson Streaming API Example

Convert JSON to Java object using Jackson JsonGenerator

package com.javainterviewpoint;

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;

public class Jackson_Streaming_Write_Example
{
    public static void main(String args[])
    {
        try
        {
            //Create a JsonFactory
            JsonFactory factory = new JsonFactory();
            
            //JsonGenerator for writing the JSON File
            JsonGenerator generator = factory.
                    createJsonGenerator(new File("C:\\user.json"), JsonEncoding.UTF8);
            
            //Writing a JSON opening brace {
            generator.writeStartObject();
            
            //Writing String key and String value - "Name":"JIP"
            generator.writeStringField("Name","JIP");
            
            //Writing String key and Integer value - "Age":111
            generator.writeNumberField("Age",111);
            
            generator.writeFieldName("FavouriteSports");
            
            //Writing a JSON array opening brace [
            generator.writeStartArray();
            
            //Writing array value
            generator.writeString("Football");
            generator.writeString("Cricket");
            generator.writeString("Chess");
            generator.writeString("Baseball");
            
            //Writing a JSON array closing brace ]
            generator.writeEndArray();
            
            //Writing a JSON closing brace }
            generator.writeEndObject();
            
            generator.close();
        } catch (JsonParseException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • Create a JsonFactory, from which we will be getting JsonGenerator
JsonFactory factory = new JsonFactory();
  • The createJsonGenerator() method of the factory returns the JsonGenertor object, we need to pass the input file which you want to read and encoding.
 JsonGenerator generator = factory.
                    createJsonGenerator(new File("C:\\user.json"), JsonEncoding.UTF8);
  • Now let us start writing the JSON using JsonGenerator, we need to write each and every token
    1. generator.writeStartObject() –> Write the starting brace “{“
    2. generator.writeStringField(“Name”,”JIP”) –> Write String key(Name) and String value(JIP)
    3. generator.writeNumberField(“Age”,111) –> Writing String key(Age) and Integer value(111)
    4. generator.writeFieldName(“FavouriteSports”) –> Writing String key alone(FavouriteSports)
    5. generator.writeStartArray() –> Writing open brace of the array “[“
    6. generator.writeString(“Football”) –> Writing the values of the array (Football, Cricket,Chess,Baseball).
    7. generator.writeEndArray() –> Writing the end brace of the array “]”
    8. generator.writeEndObject() –> Write the end brace “}”
  • Finally close the generator Object using the close() method
generator.close();

Output :
In the user.json file we will be having the below content

{"Name":"JIP","Age":111,"FavouriteSports":["Football","Cricket","Chess","Baseball"]}

Filed Under: Core Java, Java Tagged With: Jackson, Jackson Streaming API, Read JSON, Write JSON

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·