Gson là thư viện chuyển đối tượng Java sang biểu diễn JSON. Lớp chính là Gson tạo bằng new Gson(), GsonBuilder dùng để tạo instance Gson tùy chỉnh.
Có thể ghi chuỗi JSON ra file dùng phương thức toJson() của lớp Gson nhận thêm tham số Writer.
Ví dụ minh họa
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("Ghi JSON ra file thành công");
System.out.println(student);
}
}
// Lớp Student
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;
}
// getters/setters...
public String toString() {
return "Student[ firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", address=" + address + " ]";
}
}
File Student.json được tạo
{"firstName":"Raja","lastName":"Ramesh","age":30,"address":"Hyderabad"}
Kết quả console
Ghi JSON ra file thành công Student[ firstName=Raja, lastName=Ramesh, age=30, address=Hyderabad ]
Lưu ý: Dùng GsonBuilder().setPrettyPrinting().create() nếu muốn JSON trong file có indentation. Luôn đóng Writer (try-with-resources từ Java 7).