How can we read & 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 sequential read and write standard. The JsonWriter and JsonReader are the core classes built for streaming write and read in 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. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document.

Write to a file using JsonWriter

Example

import java.io.*;
import com.google.gson.stream.*;
public class JsonWriterTest {
   public static void main(String args[]) {
      JsonWriter writer;
      try {
         writer = new JsonWriter(new FileWriter("input.json"));
         writer.beginObject();
         writer.name("name").value("Adithya");
         writer.name("age").value(25);
         writer.name("technologies");
         writer.beginArray();
         writer.value("Java");
         writer.value("Scala");
         writer.value("Python");
         writer.endArray();
         writer.endObject();
         writer.close();
         System.out.println("Data write to a file successfully");
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Output

Data write to a file successfully


Read a file using JsonReader

Example

import java.io.*;
import com.google.gson.stream.*;
public class JsonReaderTest {
   public static void main(String args[]) {
      JsonReader reader;
      try {
         reader = new JsonReader(new FileReader("input.json"));
         reader.beginObject();
         while(reader.hasNext()) {
            String name = reader.nextName();
            if(name.equals("name")) {
               System.out.println(reader.nextString());
            } else if(name.equals("age")) {
               System.out.println(reader.nextInt());
            } else if(name.equals("technologies")) {
               reader.beginArray();
               while(reader.hasNext()) {
                  System.out.println(reader.nextString());
               }
               reader.endArray();
            } else {
               reader.skipValue();
            }
         }
         reader.endObject();
         reader.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Output

Adithya
25
Java
Scala
Python

Updated on: 06-Jul-2020

751 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements