📘 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
Read a JSON file Using GSON in Java
[
{
"studentId": 100,
"studentName": "student1"
},
{
"studentId": 200,
"studentName": "student2"
},
{
"studentId": 300,
"studentName": "student3"
},
{
"studentId": 400,
"studentName": "student4"
},
{
"studentId": 500,
"studentName": "student5"
}
]
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());
}
}
}
}
}
********************
100
student1
********************
200
student2
********************
300
student3
********************
400
student4
********************
500
student5
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());
}
}
Comments
Post a Comment
Leave Comment