Java GSON Tree Model API - Read and Write Example

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.

Comments