如何在 Java 中使用 Gson 庫將 JSON 字串寫入檔案?


Gson 是一款庫,可用於將 Java 物件轉換為 JSON 表示。要使用的主要類是Gson ,可以透過呼叫new Gson()建立,而GsonBuilder 類可用於建立 Gson 例項。

我們可以在下面的示例中使用Gson 類的toJson()方法將 JSON 字串寫入檔案

示例

import java.io.*;
import com.google.gson.*;
public class JSONToFileTest {
   public static void main(String[] args) throws IOException {
      Gson gson = new Gson();
      FileWriter fileWriter = new FileWriter("Student.json");
      Student student = new Student("Raja", "Ramesh", 30, "Hyderabad");
      gson.toJson(student, fileWriter);
      fileWriter.close();
      System.out.println("JSON string write to a file successfully");
      System.out.println(student);
   }
}
// Student class
class Student {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   public Student(String firstName, String lastName, int age, String address) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
  public int getAge() {
     return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String toString() {
      return "Student[ " +
               "firstName = " + firstName +
               ", lastName = " + lastName +
               ", age = " + age +
               ", address = " + address +
             " ]";
   }
}


Student.json 檔案


輸出

JSON string write to a file successfully
Student[ firstName = Raja, lastName = Ramesh, age = 30, address = Hyderabad ]

更新於:2020 年 07 月 04 日

1K+ 檢視

開啟你的職業生涯

完成課程獲取認證

開始
廣告