A Gson is a library that can be used to convert Java Objects to JSON representation. The primary class to use is Gson which we can create by calling the new Gson() and the GsonBuilder class can be used to create a Gson instance.
We can write a JSON string to file using the toJson() method of Gson class in the below example
Example
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 file
Output
JSON string write to a file successfully Student[ firstName = Raja, lastName = Ramesh, age = 30, address = Hyderabad ]