如何使用 Java 中的 Gson 库将 JSON 字符串写入文件?
javajsonobject oriented programmingprogramming更新于 2025/7/6 13:32:17
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 classclass 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 ]
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

