Gson은 Java 개체를 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 ]
