Джексон - Примеры моделей потоковой передачи
В этом руководстве Джексона показано, как использоватьJsonGenerator для записи строки JSON и массива JSON в файл, кроме того, читать его с помощьюJsonParser.
API потоковой передачи Jackson
-
JsonGenerator- записать JSON -
+JsonParser +- Разобрать JSON
Note
Потоковый режим Джексона - это базовая модель обработки, на которой основаны какdata-binding, так иTree Model. Это лучшая производительность и контроль над анализом JSON и генерацией JSON.
Протестировано с Джексоном 2.9.8
1. JsonGenerator - запись JSON
1.1 Write JSON to a file.
JacksonExample1.java
package com.example;
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", "example"); // "name" : "example"
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();
}
}
}
Выход
c:\projects\user.json
{"name":"example","age":38,"messages":["msg 1","msg 2","msg 3"]}
2. JsonGenerator - запись массива JSON
2.1 1.1 Write JSON array to a file.
JacksonExample2.java
package com.example;
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", "example"); // "name" : "example"
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();
}
}
}
Выход
c:\projects\user2.json
[
{
"name" : "example",
"age" : 38,
"messages" : [ "msg 1", "msg 2", "msg 3" ]
}, {
"name" : "lap",
"age" : 5,
"messages" : [ "msg a", "msg b", "msg c" ]
}
]
3. JsonParser - чтение JSON
Token
В режиме потоковой передачи Джексона он разбивает строку JSON на список токенов, и каждый токен будет обрабатываться инкрементально. Например,
{
"name":"example"
}
-
Токен 1 = \ {
-
Токен 2 = имя
-
Токен 3 = пример
-
Токен 4 =}
3.1 JsonParser example to parse a JSON file.
c:\projects\user.json
{"name":"example","age":38,"messages":["msg 1","msg 2","msg 3"]}
JacksonExample3.java
package com.example;
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();
}
}
}
Выход
example 38 msg 1 msg 2 msg 3
4. JsonParser - чтение массива JSON
4.1 JsonParser example to parse a JSON array file.
c:\projects\user2.json
[
{
"name" : "example",
"age" : 38,
"messages" : [ "msg 1", "msg 2", "msg 3" ]
}, {
"name" : "lap",
"age" : 5,
"messages" : [ "msg a", "msg b", "msg c" ]
}
]
JacksonExample4.java
package com.example;
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();
}
}
}
Выход
example 38 msg 1 msg 2 msg 3 lap 5 msg a msg b msg c
Note
БольшеJackson examples