如何在 Java 中使用 Gson 流式 API 读取和写入文件?
我们可以使用**Gson 流式 API**读取和写入文件,它基于顺序读取和写入标准。**JsonWriter**和**JsonReader**是为流式写入和读取而在**流式 API**中构建的核心类。**JsonWriter**一次写入一个标记到流中的 JSON 编码值。该流包括文字值(**字符串、数字、布尔值和空值**)以及对象和数组的**开始**和**结束****分隔符**,而**JsonReader**将 JSON 编码值读取为标记流。此流包括**文字****值**(**字符串、数字、布尔值和空值**)以及对象和数组的**开始**和**结束**分隔符。标记以**深度优先顺序**遍历,与它们在 JSON 文档中出现的顺序相同。
使用 JsonWriter 写入文件
示例
import java.io.*;
import com.google.gson.stream.*;
public class JsonWriterTest {
public static void main(String args[]) {
JsonWriter writer;
try {
writer = new JsonWriter(new FileWriter("input.json"));
writer.beginObject();
writer.name("name").value("Adithya");
writer.name("age").value(25);
writer.name("technologies");
writer.beginArray();
writer.value("Java");
writer.value("Scala");
writer.value("Python");
writer.endArray();
writer.endObject();
writer.close();
System.out.println("Data write to a file successfully");
} catch(Exception e) {
e.printStackTrace();
}
}
}输出
Data write to a file successfully
使用 JsonReader 读取文件
示例
import java.io.*;
import com.google.gson.stream.*;
public class JsonReaderTest {
public static void main(String args[]) {
JsonReader reader;
try {
reader = new JsonReader(new FileReader("input.json"));
reader.beginObject();
while(reader.hasNext()) {
String name = reader.nextName();
if(name.equals("name")) {
System.out.println(reader.nextString());
} else if(name.equals("age")) {
System.out.println(reader.nextInt());
} else if(name.equals("technologies")) {
reader.beginArray();
while(reader.hasNext()) {
System.out.println(reader.nextString());
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
reader.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}输出
Adithya 25 Java Scala Python
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP