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 JSONJsonParser– 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.favtuts.json;
import java.io.File;
import java.io.IOException;
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;
public class JacksonStreamingModelExamples {
public static void main(String[] args) {
writeJsonToFile();
}
static void writeJsonToFile() {
ObjectMapper mapper = new ObjectMapper();
try (JsonGenerator jGenerator = mapper.getFactory()
.createGenerator(new File("/home/tvt/workspace/favtuts/user.json"),
JsonEncoding.UTF8)) {
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("name", "favtuts"); // "name" : "favtuts"
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":"favtuts","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.favtuts.json;
import java.io.File;
import java.io.IOException;
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;
public class JacksonStreamingModelExamples {
public static void main(String[] args) {
// writeJSONToFile();
writeJSONarrayToFile();
}
static void writeJSONarrayToFile() {
ObjectMapper mapper = new ObjectMapper();
try (JsonGenerator jGenerator = mapper.getFactory()
.createGenerator(new File("/home/tvt/workspace/favtuts/user2.json"),
JsonEncoding.UTF8)) {
// pretty print
jGenerator.useDefaultPrettyPrinter();
// start array
jGenerator.writeStartArray(); // [
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("name", "favtuts"); // "name" : "favtuts"
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": "favtuts",
"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":"favtuts"
}
- Token 1 = {
- Token 2 = name
- Token 3 = favtuts
- Token 4 = }
3.1 JsonParser example to parse a JSON file.
c:\\projects\\user.json
{"name":"favtuts","age":38,"messages":["msg 1","msg 2","msg 3"]}
JacksonExample3.java
package com.favtuts.json;
import java.io.File;
import java.io.IOException;
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;
public class JacksonStreamingModelExamples {
public static void main(String[] args) {
readJSONfromFile();
}
static void readJSONfromFile() {
try (JsonParser jParser = new JsonFactory()
.createParser(new File("/home/tvt/workspace/favtuts/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
favtuts
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": "favtuts",
"age": 38,
"messages": [
"msg 1",
"msg 2",
"msg 3"
]
},
{
"name": "lap",
"age": 5,
"messages": [
"msg a",
"msg b",
"msg c"
]
}
]
JacksonExample4.java
package com.favtuts.json;
import java.io.File;
import java.io.IOException;
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;
public class JacksonStreamingModelExamples {
public static void main(String[] args) {
readJSONarrayFromFile();
}
static void readJSONarrayFromFile() {
try (JsonParser jParser = new JsonFactory()
.createParser(new File("/home/tvt/workspace/favtuts/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
favtuts
38
msg 1
msg 2
msg 3
lap
5
msg a
msg b
msg c
Note
More Jackson examples
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-basic/json