Jackson Streaming API examples
This article shows how to use Jackson’s Streaming API for both reading from and writing to JSON.
Jackson’s Streaming API
JsonGenerator
– Write JSON dataJsonParser
– Read and Parse JSON data
Table of contents:
- 1. Download Jackson
- 2. Write JSON using JsonGenerator
- 2. Write JSON Array using JsonGenerator
- 3. Read JSON using JsonParser
- 4. Read JSON Array using JsonParser
- 5. Download Source Code
- 6. References
P.S Tested with Jackson 2.17.0
Note
Jackson’s Streaming API are efficient way of processing JSON data without load the entire document into memory. This is useful for parsing large JSON files.
1. Download Jackson
Declares jackson-databind
at pom.xml
.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.0</version>
</dependency>
2. Write JSON using JsonGenerator
The following example demostrate the use of Jackson’s JsonGenerator
object to write a simple JSON to a String
and print them out.
package com.mkyong.json.jackson.streaming;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import java.io.IOException;
import java.io.StringWriter;
public class JsonGeneratorExample1 {
public static void main(String[] args) {
JsonFactory factory = new JsonFactory();
StringWriter writer = new StringWriter();
try (JsonGenerator generator = factory.createGenerator(writer)) {
generator.writeStartObject(); // start root object
generator.writeStringField("name", "mkyong");
generator.writeNumberField("age", 42);
generator.writeEndObject(); // end root object
generator.close();
String jsonOutput = writer.toString();
System.out.println(jsonOutput);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Output
{"name":"mkyong","age":42}
2. Write JSON Array using JsonGenerator
The following example demostrate the use of Jackson’s JsonGenerator
object to write JSON array to a file named user.json
.
package com.mkyong.json.jackson.streaming;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class JsonGeneratorExample2 {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try (JsonGenerator generator =
mapper.getFactory().createGenerator(
new File("user.json"), JsonEncoding.UTF8)) {
// pretty print
generator.useDefaultPrettyPrinter();
// start array
generator.writeStartArray(); // [
generator.writeStartObject(); // {
generator.writeStringField("name", "mkyong"); // "name" : "mkyong"
generator.writeNumberField("age", 42); // "age" : 42
generator.writeFieldName("messages"); // "messages" :
generator.writeStartArray(); // [
generator.writeString("msg 1"); // "msg 1"
generator.writeString("msg 2"); // "msg 2"
generator.writeString("msg 3"); // "msg 3"
generator.writeEndArray(); // ]
generator.writeEndObject(); // }
// next object
generator.writeStartObject(); // {
generator.writeStringField("name", "ah pig"); // "name" : "ah pig"
generator.writeNumberField("age", 30); // "age" : 30
generator.writeFieldName("messages"); // "messages" :
generator.writeStartArray(); // [
generator.writeString("a"); // "a"
generator.writeString("b"); // "b"
generator.writeString("c"); // "c"
generator.writeEndArray(); // ]
generator.writeEndObject(); // }
generator.writeEndArray(); // ]
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Output
[
{
"name" : "mkyong",
"age" : 42,
"messages" : [ "msg 1", "msg 2", "msg 3" ]
},
{
"name" : "ah pig",
"age" : 30,
"messages" : [ "a", "b", "c" ]
}
]
3. Read JSON using JsonParser
The following example demostrates the use of Jackson’s JsonParser
object to Read a JSON and print it out.
{
"name":"mkyong",
"age":42
}
package com.mkyong.json.jackson.streaming;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.IOException;
import java.io.StringReader;
public class JsonParserExample1 {
public static void main(String[] args) {
String json = "{\"name\":\"mkyong\",\"age\":42}";
JsonFactory factory = new JsonFactory();
try (JsonParser parser = factory.createParser(new StringReader(json))) {
while (parser.nextToken() != JsonToken.END_OBJECT) {
// Deprecated alias of currentName().
// Deprecated Since 2.17 use currentName instead.
// String fieldName = parser.getCurrentName();
String fieldName = parser.currentName();
if ("name".equals(fieldName)) {
parser.nextToken();
System.out.println("Name: " + parser.getText());
} else if ("age".equals(fieldName)) {
parser.nextToken();
System.out.println("Age: " + parser.getIntValue());
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Output
Name: mkyong
Age: 42
Token
In the 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 = }
4. Read JSON Array using JsonParser
The following example demostrate the use of Jackson’s JsonParser
object to read JSON from a file named user.json
and parse the JSON and print the token one by one.
[
{
"name" : "mkyong",
"age" : 42,
"messages" : [ "msg 1", "msg 2", "msg 3" ]
},
{
"name" : "ah pig",
"age" : 30,
"messages" : [ "a", "b", "c" ]
}
]
package com.mkyong.json.jackson.streaming;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.File;
import java.io.IOException;
public class JsonParserExample2 {
public static void main(String[] args) {
try (JsonParser jParser = new JsonFactory()
.createParser(new File("user.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.currentName();
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 (IOException e) {
throw new RuntimeException(e);
}
}
}
Output
mkyong
42
msg 1
msg 2
msg 3
ah pig
30
a
b
c
5. Download Source Code
$ git clone https://github.com/mkyong/java-json
$ cd jackson/streaming