📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Check out complete google GSON tutorial at https://www.javaguides.net/p/google-gson-tutorial.html.
Write JSON into a File Using GSON in Java
package net.guides;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
class Student {
private long studentId;
private String studentName;
public Student(long studentId, String studentName) {
super();
this.studentId = studentId;
this.studentName = studentName;
}
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
public class GsonTreeModelWrite {
public static void main(String[] args) throws FileNotFoundException, IOException {
List < Student > students = new ArrayList < > ();
Student student1 = new Student(100, "student1");
Student student2 = new Student(200, "student2");
Student student3 = new Student(300, "student3");
Student student4 = new Student(400, "student4");
Student student5 = new Student(500, "student5");
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
students.add(student5);
String fileName = "src/main/resources/students.json";
Path path = Paths.get(fileName);
try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement tree = gson.toJsonTree(students);
gson.toJson(tree, writer);
}
System.out.println("Students written to file");
}
}
[
{
"studentId": 100,
"studentName": "student1"
},
{
"studentId": 200,
"studentName": "student2"
},
{
"studentId": 300,
"studentName": "student3"
},
{
"studentId": 400,
"studentName": "student4"
},
{
"studentId": 500,
"studentName": "student5"
}
]
JsonElement tree = gson.toJsonTree(students);
gson.toJson(tree, writer);
Comments
Post a Comment
Leave Comment