Jackson 简明教程
Jackson - Streaming API
流式 API 以分离事件形式读取和写入 JSON 内容。JsonParser 读取数据,而 JsonGenerator 则写入数据。这是三者中功能最强大的方法,也是读取/写入操作中最省时和最快的。它类似于 XML 的 Stax 解析器。
Streaming API reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML.
在本文中,我们将展示使用 Jackson 流式 API 来读取和写入 JSON 数据。流式 API 使用令牌的概念,并且每个 Json 细节都必须小心处理。以下是我们将在示例中使用的两个类:
In this Article, we’ll showcase using Jackson streaming APIs to read and write JSON data. Streaming API works with concept of token and every details of Json is to be handle carefuly. Following are two class which we’ll use in the examples:
-
JsonGenerator - Write to JSON String.
-
JsonParser - Parse JSON String.
Writing JSON using JsonGenerator
使用 JsonGenerator 非常简单。首先使用 JsonFactory.createJsonGenerator() 方法创建 JsonGenerator,然后使用其 write***() 方法写入每个 json 值。
Using JsonGenerator is pretty simple. First create the JsonGenerator using JsonFactory.createJsonGenerator() method and use it’s write***() methods to write each json value.
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(
"student.json"), JsonEncoding.UTF8);
// {
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField("name", "Mahesh Kumar");
让我们看看 JsonGenerator 在操作中。在 C:>Jackson_WORKSPACE 中创建名为 JacksonTester 的 java 类文件。
Let’s see JsonGenerator in action. Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
文件:JacksonTester.java
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
try {
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File("student.json"), JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField("name", "Mahesh Kumar");
// "age" : 21
jsonGenerator.writeNumberField("age", 21);
// "verified" : false
jsonGenerator.writeBooleanField("verified", false);
// "marks" : [100, 90, 85]
jsonGenerator.writeFieldName("marks");
// [
jsonGenerator.writeStartArray();
// 100, 90, 85
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
// ]
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> dataMap = mapper.readValue(new File("student.json"), Map.class);
System.out.println(dataMap.get("name"));
System.out.println(dataMap.get("age"));
System.out.println(dataMap.get("verified"));
System.out.println(dataMap.get("marks"));
}
catch (JsonParseException e) { e.printStackTrace(); }
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
Verify the result
Verify the result
使用 javac 编译器编译类,如下所示:
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
现在运行 jacksonTester 查看结果:
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
验证输出
Verify the Output
Mahesh Kumar
21
false
[100, 90, 85]
Reading JSON using JsonParser
使用 JsonParser 也很简单。首先使用 JsonFactory.createJsonParser() 方法创建 JsonParser,然后使用其 nextToken() 方法读取每个 json 字符串作为令牌。检查每个令牌并相应处理。
Using JsonParser is again pretty simple. First create the JsonParser using JsonFactory.createJsonParser() method and use it’s nextToken() methods to read each json string as token. Check each token and process accordingly
JsonFactory jasonFactory = new JsonFactory();
JsonParser jsonParser = jasonFactory.createJsonParser(new File("student.json"));
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
//get the current token
String fieldname = jsonParser.getCurrentName();
if ("name".equals(fieldname)) {
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
}
让我们看看 JsonParser 在操作中。在 C:>Jackson_WORKSPACE 中创建名为 JacksonTester 的 java 类文件。
Let’s see JsonParser in action. Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
文件:JacksonTester.java
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(
"student.json"), JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Mahesh Kumar");
jsonGenerator.writeNumberField("age", 21);
jsonGenerator.writeBooleanField("verified", false);
jsonGenerator.writeFieldName("marks");
jsonGenerator.writeStartArray(); // [
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
JsonParser jsonParser = jsonFactory.createParser(new File("student.json"));
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
//get the current token
String fieldname = jsonParser.getCurrentName();
if ("name".equals(fieldname)) {
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
if("age".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getNumberValue());
}
if("verified".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getBooleanValue());
}
if("marks".equals(fieldname)){
//move to [
jsonParser.nextToken();
// loop till token equal to "]"
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
System.out.println(jsonParser.getNumberValue());
}
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Verify the result
Verify the result
使用 javac 编译器编译类,如下所示:
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
现在运行 jacksonTester 查看结果:
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
验证输出
Verify the Output
Mahesh Kumar
21
false
[100, 90, 85]