Read and Write a File Using Gson Streaming API in Java



We can read and write a file using Gson streaming API, and it is based on the sequential read and write standard. The JsonWriter and JsonReader are the core classes built for streaming write and read in Streaming API.

Reading & Writing a File using Gson Streaming API

The JsonWriter writes a JSON-encoded value to a stream, one token at a time. The stream includes both literal values (strings, numbers, booleans, and nulls) as well as begin and end delimiters of objects and arrays, and JsonReader reads a JSON-encoded value as a stream of tokens. The tokens are traversed in depth-first order, the same order that they appear in the JSON document.

To use the Gson we need to include it to our project. If you are using Maven, add this to your pom.xml file:

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.9</version>
</dependency>

If you do not use Maven, you can download the jar file from here.

Steps 

Following are the steps to read and write a file using Gson streaming API in Java -

  • Import the Gson library and other required classes.
  • After importing the Gson library, create a class Person with fields for name and age.
  • Create a JsonWriter object to write the JSON data to a file.
  • Use the beginObject() method to start writing a JSON object.
  • Use the name(), value(), and endObject() methods to write the JSON data.
  • Close the JsonWriter object.
  • Create a JsonReader object to read the JSON data from the file.
  • Use the beginObject() method to start reading a JSON object.
  • Use the nextName(), nextString(), and endObject() methods to read the JSON data.
  • Close the JsonReader object.
  • Lastly, print the Person object.

Example

In the below example, we will create a JSON file named person.json and we would write the name and age fields to it using the JsonWriter class. Then, we read the JSON data from the file using the JsonReader class and print the values.

Following is the code to read and write a file using Gson streaming API in Java:

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class GsonStreamingExample {
   public static void main(String[] args) {
      // Create a JSON file
      String jsonFilePath = "person.json";

      // Create a JsonWriter object to write the JSON data to a file
      try (JsonWriter writer = new JsonWriter(new FileWriter(jsonFilePath))) {
         // Start writing a JSON object
         writer.beginObject();
         // Write the name and age fields
         writer.name("name").value("Ansh");
         writer.name("age").value(23);
         // End the JSON object
         writer.endObject();
      } catch (IOException e) {
         e.printStackTrace();
      }

      // Create a JsonReader object to read the JSON data from the file
      try (JsonReader reader = new JsonReader(new FileReader(jsonFilePath))) {
         // Start reading a JSON object
         reader.beginObject();
         // Read the name and age fields
         String name = null;
         int age = 0;
         while (reader.hasNext()) {
            String fieldName = reader.nextName();
            if (fieldName.equals("name")) {
               name = reader.nextString();
            } else if (fieldName.equals("age")) {
               age = reader.nextInt();
            }
         }
         // End the JSON object
         reader.endObject();

         // Print the Person object
         System.out.println("Name: " + name);
         System.out.println("Age: " + age);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Following is the output of the above code:

Name: Ansh
Age: 23
Updated on: 2025-05-12T13:06:24+05:30

985 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements