Reading JSON in a streaming way

This post explain how to stream a json file. We need to create an instance of JsonFactory, as shown below
JsonFactory jsonFactory = new JsonFactory();

by which we can create a parser instance (i.e., JsonParser) to read the json file, as shown below
JsonParser jsonParser = jsonFactory.createParser(file);

Each element whether start and end of the object, start and end of array, field name and field values are represented by JsonToken enums. We retrieve the elements by the help of jsonParser, as shown below

a null value indicates the end of line.

We get the field name and field value in String format using the jsonParser as shown below

Main Code


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

public class ProcessingDemo1 {
    public static void main(String[] args) throws JsonParseException, IOException {
        File file = new File("jsondata.json");
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jsonParser = jsonFactory.createParser(file);
        JsonToken jsonToken = jsonParser.nextToken();
        while(jsonToken != null) {
            switch(jsonToken) {
                case START_OBJECT: System.out.println("Object Started");
                case END_OBJECT: System.out.println("Object Ended");
                case START_ARRAY: System.out.println("Array Started");
                case END_ARRAY: System.out.println("Array Ended");
                case FIELD_NAME: System.out.println("Key field: " + jsonParser.getText());
                case VALUE_FALSE:
                case VALUE_NULL:
                case VALUE_NUMBER_FLOAT:
                case VALUE_NUMBER_INT:
                case VALUE_STRING:
                case VALUE_TRUE:
                                default:System.out.println("Key value: " + jsonParser.getText());
            jsonToken = jsonParser.nextToken();


    "firstName": "Duke",
    "lastName": "Java",
    "age": 18,
    "streetAddress": "100 Internet Dr",
    "city": "JavaTown",
    "state": "JA",
    "postalCode": "12345",
    "phoneNumbers": [
        { "Mobile": "111-111-1111" },
        { "Home": "222-222-2222" }


Object Started
Key field: firstName
Key value: Duke
Key field: lastName
Key value: Java
Key field: age
Key value: 18
Key field: streetAddress
Key value: 100 Internet Dr
Key field: city
Key value: JavaTown
Key field: state
Key value: JA
Key field: postalCode
Key value: 12345
Key field: phoneNumbers
Array Started
Object Started
Key field: Mobile
Key value: 111-111-1111
Object Ended
Object Started
Key field: Home
Key value: 222-222-2222
Object Ended
Array Ended
Object Ended

Leave a Reply