Gson เป็นไลบรารีแปลง Java Objects เป็น JSON Representation คลาสหลักคือ Gson สร้างด้วย new Gson() หรือใช้ GsonBuilder สร้าง Instance เขียน JSON String ลงไฟล์ด้วยเมธอด toJson() ของ Gson Class ส่ง Writer เข้าไป
ตัวอย่าง: Write JSON to File
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) {
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 + " ]";
}
}
ไฟล์ Student.json ที่สร้าง
{"firstName":"Raja","lastName":"Ramesh","age":30,"address":"Hyderabad"}
ผลลัพธ์ Console
JSON string write to a file successfully
Student[ firstName = Raja, lastName = Ramesh, age = 30, address = Hyderabad ]
Pretty Print Version:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.toJson(student, fileWriter);
จะได้ไฟล์ JSON ที่ Format สวยอ่านง่าย