如何在 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


Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

使用 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

更新于: 2020-07-06

911 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始
广告