Gson เป็นไลบรารี่ที่สามารถใช้เพื่อ แปลง Java Objects เป็นการแสดง JSON . คลาสหลักที่ใช้คือ Gson ซึ่งเราสร้างได้โดยการเรียก new Gson() และ GsonBuilder สามารถใช้คลาสเพื่อสร้างอินสแตนซ์ Gson ได้
เราสามารถเขียนสตริง JSON ลงในไฟล์ได้ โดยใช้ toJson() วิธีการของ Gson ในตัวอย่างด้านล่าง
ตัวอย่าง
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 ]
