Write JSON to file in Java using Gson
In this example we will create a Java object and then write it to a file in JSON
format using Gson
library.
To parse JSON using Gson library, you need to use gson-2.9.0 jar
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.0</version> </dependency>
Java class used to represent the JSON
import java.util.List; public class Student { private int id; private String name; private int age; private List<String> emailaddress; // removed getter and setter @Override public String toString() { return "Student [id=" + id + ", name=" + name + "," +" age=" + age + ", emailaddress=" + emailaddress + "]"; } }
Create Java object and write it to file in JSON format.
import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class TestGsonFileWriter { public static void main(String[] args) { Student student = new Student(); student.setId(123); student.setName("George Bush"); student.setAge(40); List<String> emailaddress = new ArrayList<>(); emailaddress.add("jbush@yahoo.com"); emailaddress.add("jbush@gmail.com"); student.setEmailaddress(emailaddress); Gson gson = new GsonBuilder().setPrettyPrinting().create(); try (FileWriter writer = new FileWriter("E:\\student.json")) { gson.toJson(student, writer); } catch (IOException e) { e.printStackTrace(); } } }
Output :
If you see under E: or whatever directory you use to write JSON file, you will see below JSON file is generated
{ "id": 123, "name": "George Bush", "age": 40, "emailaddress": [ "jbush@yahoo.com", "jbush@gmail.com" ] }