Main Tutorials

Jackson – Streaming Model examples

This Jackson tutorial show you how to use JsonGenerator to write JSON string and JSON array into a file, furthermore, read it with JsonParser

Jackson Streaming APIs

  • JsonGenerator – Write JSON
  • JsonParser – Parse JSON
Note
The Jackson streaming mode is the underlying processing model that data-binding and Tree Model both build upon. It is the best performance and control over the JSON parsing and JSON generation.

Tested with Jackson 2.9.8

1. JsonGenerator – Write JSON

1.1 Write JSON to a file.

JacksonExample1.java

package com.mkyong;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

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

public class JacksonExample1 {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        try (JsonGenerator jGenerator =
                     mapper.getFactory().createGenerator(
                             new File("c:\\projects\\user.json")
                             , JsonEncoding.UTF8)) {
            
            jGenerator.writeStartObject();                                  // {

            jGenerator.writeStringField("name", "mkyong");  				// "name" : "mkyong"
            jGenerator.writeNumberField("age", 38);         				// "age" : 38

            jGenerator.writeFieldName("messages");                          // "messages" :

            jGenerator.writeStartArray();                                   // [

            jGenerator.writeString("msg 1");                            		// "msg 1"
            jGenerator.writeString("msg 2");                            		// "msg 2"
            jGenerator.writeString("msg 3");                            		// "msg 3"

            jGenerator.writeEndArray();                                     // ]

            jGenerator.writeEndObject();                                    // }

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output

c:\\projects\\user.json

{"name":"mkyong","age":38,"messages":["msg 1","msg 2","msg 3"]}

2. JsonGenerator – Write JSON Array

2.1 1.1 Write JSON array to a file.

JacksonExample2.java

package com.mkyong;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

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

public class JacksonExample2 {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        try (JsonGenerator jGenerator =
                     mapper.getFactory().createGenerator(
                             new File("c:\\projects\\user2.json")
                             , JsonEncoding.UTF8)) {

            // pretty print
            jGenerator.useDefaultPrettyPrinter();

            // start array
            jGenerator.writeStartArray();                                   // [

            jGenerator.writeStartObject();                                  // {

            jGenerator.writeStringField("name", "mkyong");  				// "name" : "mkyong"
            jGenerator.writeNumberField("age", 38);         				// "age" : 38

            jGenerator.writeFieldName("messages");                          // "messages" :

            jGenerator.writeStartArray();                                   // [

            jGenerator.writeString("msg 1");                            	// "msg 1"
            jGenerator.writeString("msg 2");                            	// "msg 2"
            jGenerator.writeString("msg 3");                            	// "msg 3"

            jGenerator.writeEndArray();                                     // ]

            jGenerator.writeEndObject();                                    // }

            // next object, pls

            jGenerator.writeStartObject();                                  // {

            jGenerator.writeStringField("name", "lap");  					// "name" : "lap"
            jGenerator.writeNumberField("age", 5);         					// "age" : 5

            jGenerator.writeFieldName("messages");                          // "messages" :

            jGenerator.writeStartArray();                                   // [

            jGenerator.writeString("msg a");                            	// "msg a"
            jGenerator.writeString("msg b");                            	// "msg b"
            jGenerator.writeString("msg c");                            	// "msg c"

            jGenerator.writeEndArray();                                     // ]

            jGenerator.writeEndObject();                                    // }

            jGenerator.writeEndArray();                                     // ]

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output

c:\\projects\\user2.json

[ 
	{
	  "name" : "mkyong",
	  "age" : 38,
	  "messages" : [ "msg 1", "msg 2", "msg 3" ]
	}, {
	  "name" : "lap",
	  "age" : 5,
	  "messages" : [ "msg a", "msg b", "msg c" ]
	} 
]

3. JsonParser – Read JSON

Token
In Jackson streaming mode, it splits JSON string into a list of tokens, and each token will be processed incremental. For example,


{
   "name":"mkyong"
}
  • Token 1 = {
  • Token 2 = name
  • Token 3 = mkyong
  • Token 4 = }

3.1 JsonParser example to parse a JSON file.

c:\\projects\\user.json

{"name":"mkyong","age":38,"messages":["msg 1","msg 2","msg 3"]}
JacksonExample3.java

package com.mkyong;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;

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

public class JacksonExample3 {

    public static void main(String[] args) {

        try (JsonParser jParser = new JsonFactory()
				.createParser(new File("c:\\projects\\user.json"));) {

            // loop until token equal to "}"
            while (jParser.nextToken() != JsonToken.END_OBJECT) {

                String fieldname = jParser.getCurrentName();
				
                if ("name".equals(fieldname)) {
                    // current token is "name",
                    // move to next, which is "name"'s value
                    jParser.nextToken();
                    System.out.println(jParser.getText());
                }

                if ("age".equals(fieldname)) {
                    jParser.nextToken();
                    System.out.println(jParser.getIntValue());
                }

                if ("messages".equals(fieldname)) {

                    if (jParser.nextToken() == JsonToken.START_ARRAY) {
                        // messages is array, loop until token equal to "]"
                        while (jParser.nextToken() != JsonToken.END_ARRAY) {
                            System.out.println(jParser.getText());
                        }
                    }

                }

            }

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output


mkyong
38
msg 1
msg 2
msg 3

4. JsonParser – Read JSON Array

4.1 JsonParser example to parse a JSON array file.

c:\\projects\\user2.json

[ 
	{
	  "name" : "mkyong",
	  "age" : 38,
	  "messages" : [ "msg 1", "msg 2", "msg 3" ]
	}, {
	  "name" : "lap",
	  "age" : 5,
	  "messages" : [ "msg a", "msg b", "msg c" ]
	} 
]
JacksonExample4.java

package com.mkyong;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;

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

public class JacksonExample4 {

    public static void main(String[] args) {

        try (JsonParser jParser = new JsonFactory()
                .createParser(new File("c:\\projects\\user2.json"));) {

            // JSON array?
            if (jParser.nextToken() == JsonToken.START_ARRAY) {

                while (jParser.nextToken() != JsonToken.END_ARRAY) {

                    // loop until token equal to "}"
                    while (jParser.nextToken() != JsonToken.END_OBJECT) {

                        String fieldname = jParser.getCurrentName();
                        if ("name".equals(fieldname)) {
                            // current token is "name",
                            // move to next, which is "name"'s value
                            jParser.nextToken();
                            System.out.println(jParser.getText());
                        }

                        if ("age".equals(fieldname)) {
                            jParser.nextToken();
                            System.out.println(jParser.getIntValue());
                        }

                        if ("messages".equals(fieldname)) {

                            //jParser.nextToken(); // current token is "[", move next
                            if (jParser.nextToken() == JsonToken.START_ARRAY) {
                                // messages is array, loop until token equal to "]"
                                while (jParser.nextToken() != JsonToken.END_ARRAY) {
                                    System.out.println(jParser.getText());
                                }
                            }

                        }

                    }

                }
            }
            
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output


mkyong
38
msg 1
msg 2
msg 3
lap
5
msg a
msg b
msg c
Note
More Jackson examples

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Akash
2 years ago

I want to add multiple json files in my asset folder and display them
please guide

James Blant
9 years ago

Hi, the above example reads only one object. Please help me with how to read more than one object.

thanx in advance.

James Blant
9 years ago

Hi, your tutorials are always helpful.I need some help about how I can append json objects in the file instead of overwriting it.Thanx

Behrooz Amirinejad
9 years ago

i`m developing an android application that wanna send a file over internet to restful server but gets fault on writeBinary(File , -1); ;

this is my full code :

public void UploadFile(org.apache.commons.codec.binary.Base64InputStream File) throws Exception
{
try
{
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(“Content-Type”, “application/cdmi-object”);
conn.setRequestMethod(“PUT”);
conn.setDoInput(true);
conn.setDoOutput(true);
int buffSize = 5000;
conn.setChunkedStreamingMode(buffSize);
OutputStream os = conn.getOutputStream();
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createGenerator(os);
jGenerator.writeStartObject(); // {
jGenerator.writeFieldName(“metadata”);
jGenerator.writeStartObject(); // metadata:{
jGenerator.writeStringField(“fromClient”, “true”);
jGenerator.writeEndObject();// metadata:}
jGenerator.writeStringField(“valuetransferencoding”, “base64”);
jGenerator.writeFieldName(“value”);
jGenerator.writeBinary(File , -1);
jGenerator.writeEndObject(); // }
jGenerator.close();
int resultCode = conn.getResponseCode();
if (resultCode != HttpURLConnection.HTTP_OK) {

} else {
conn.disconnect();
}
}
catch(Exception e)
{
throw new Exception(e.getMessage());
}
}

San
9 years ago

instead of a file is there a way to generate it to String? I dont want to write to a file, instead wanted to create a string object which I can use to post to rest.

Raj
10 years ago

How to parse the following JSON string?
{“Response”:{“AuthenticateResponse”:{“status”:{“message”:”Authentication Sucessful”,”code”:”0.0″},”data”:{“assetid”:[“AP09Y6984″,”BR01G6028″,”CG04CW6399″,”JH05AH6102″,”NL01G7946″,”PB10CA2017″,”TN21AF6814″,”UK06CA1435″,”WB615937″,”WB67A0482″]},”auth”:{“id”:”f6b2797a747986f39b16c4c5ce27c5a8″}}}}

Please help me.

Lenin
10 years ago

How to parse the following text? retweeted_status is not an array. It is another json object.

“retweeted_status”:{
“contributors”:null
,”text”:”Sample text”
,”geo”:null,
“retweeted”:false
}

Striker
10 years ago

How to write the same json in an JSON Object?

Jeff
11 years ago

Nice!

Question: If every json string is consider token:

{
“name”:”mkyong”
}
became:
Token 1 = “{“
Token 2 = “name”
Token 3 = “mkyong”
Token 4 = “}”

Why “:” is not consider token?

Lenin
10 years ago
Reply to  Jeff

Maybe because it treats “:” as a delimiter for key and value