🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
GSON Tree model API creates a tree representation of the JSON document in memory. It builds a tree of JsonElements. JsonElement is a class representing an element of JSON. It could either be a JsonObject, a JsonArray, a JsonPrimitive, or a JsonNull.
Gson Tree Model Write Example
In the following example, we use the Gson tree model API to write Java objects into JSON.
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");
}
}
Here is the JSON has written into a file - src/main/resources/students.json:
[
{
"studentId": 100,
"studentName": "student1"
},
{
"studentId": 200,
"studentName": "student2"
},
{
"studentId": 300,
"studentName": "student3"
},
{
"studentId": 400,
"studentName": "student4"
},
{
"studentId": 500,
"studentName": "student5"
}
]
A list of student objects is serialized into JSON format.
JsonElement tree = gson.toJsonTree(students);
The toJsonTree method serializes the specified object into its equivalent representation as a tree of JsonElements.
gson.toJson(tree, writer);
Finally, we write the tree object into the file.
Gson Tree Model Read Example
In the following example, we use the Gson tree model API to read Java objects from JSON.
Let's read below students.json file which is an output of the above example.
src/main/resources/students.json:
[
{
"studentId": 100,
"studentName": "student1"
},
{
"studentId": 200,
"studentName": "student2"
},
{
"studentId": 300,
"studentName": "student3"
},
{
"studentId": 400,
"studentName": "student4"
},
{
"studentId": 500,
"studentName": "student5"
}
]
Here is the complete code:
package net.guides;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GsonTreeModelRead {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = "src/main/resources/students.json";
Path path = Paths.get(fileName);
try (Reader reader = Files.newBufferedReader(path,
StandardCharsets.UTF_8)) {
JsonParser parser = new JsonParser();
JsonElement tree = parser.parse(reader);
JsonArray array = tree.getAsJsonArray();
for (JsonElement element: array) {
if (element.isJsonObject()) {
JsonObject car = element.getAsJsonObject();
System.out.println("********************");
System.out.println(car.get("studentId").getAsLong());
System.out.println(car.get("studentName").getAsString());
}
}
}
}
}
Output:
********************
100
student1
********************
200
student2
********************
300
student3
********************
400
student4
********************
500
student5
In the example, we read JSON data from a file into a tree of JsonElements.
JsonParser parser = new JsonParser();
JsonElement tree = parser.parse(reader);
JsonParser parses JSON into a tree structure of JsonElements.
JsonArray array = tree.getAsJsonArray();
We get the tree as JsonArray.
for (JsonElement element: array) {
if (element.isJsonObject()) {
JsonObject car = element.getAsJsonObject();
System.out.println("********************");
System.out.println(car.get("studentId").getAsLong());
System.out.println(car.get("studentName").getAsString());
}
}
We go through the JsonArray and print the contents of its elements.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment