GSON Streaming API Reading and Writing Example

Gson Streaming API is used to process large JSON objects and is available via the JsonReader and JsonWriter classes. This streaming approach is very useful in situations where it is not desirable to load complete object model in memory, because of the danger of getting an out of memory exception when reading your JSON document. The following tutorial shows you how to read and write json data from and to a stream.

Gson – Json Stream Writer

We are building a JSON document using the JsonWriter class. This class exposes some methods to create a JSON document. This process is much more error prone because you can easily forget to close your objects or arrays. But if configured correctly its much more faster and uses less memory than when you create your json via data-binding.

package com.memorynotfound.json;

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

public class GsonStreamWriter {

    public static void main(String... args){

        JsonWriter writer;
        try {
            writer = new JsonWriter(new FileWriter("result.json"));

            writer.beginObject();                   //  {
            writer.name("name").value("BMW");       //      "name": "BMW"
            writer.name("model").value("X1");       //      "model": "X1"
            writer.name("year").value(2016);        //      "year": 2016

            writer.name("colors");                  //      "colors":
            writer.beginArray();                    //      [
            writer.value("WHITE");                  //          "WHITE"
            writer.value("BLACK");                  //          "BLACK"
            writer.value("GRAY");                   //          "GRAY"
            writer.endArray();                      //      ]

            writer.endObject();                     //  }
            writer.close();

        } catch (IOException e) {
            System.err.print(e.getMessage());
        }

    }
}

The previous code creates the following JSON file.

{"name":"BMW","model":"X1","year":"2016","colors":["WHITE","BLACK","GRAY"]}

Gson – Json Stream Reader

We can use the JsonReader to read the json from a file. While the hasNext() method of the JsonReader returns true, we can process the JSON Document. We read a JSON node by calling the nextName() method. This returns a name of the node. When we find a node we are interested we can process the data using the nextString() method. This returns the value of the node.

package com.memorynotfound.json;

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

public class GsonStreamReader {

    public static void main(String... args){

        JsonReader reader;
        try {
            reader = new JsonReader(new FileReader("result.json"));
            reader.beginObject();

            while (reader.hasNext()){
                String name = reader.nextName();

                if ("name".equals(name)){
                    System.out.println(reader.nextString());
                } else if ("model".equals(name)){
                    System.out.println(reader.nextString());
                } else if ("year".equals(name)){
                    System.out.println(reader.nextString());
                } else if ("colors".equals(name)){

                    reader.beginArray();
                    while (reader.hasNext()){
                        System.out.println("\t" + reader.nextString());
                    }
                    reader.endArray();

                } else {
                    reader.skipValue();
                }
            }

            reader.endObject();
            reader.close();

        } catch (FileNotFoundException e) {
            System.err.print(e.getMessage());
        } catch (IOException e) {
            System.err.print(e.getMessage());
        }
    }
}

The previous code generates the following output.

BMW
X1
2016
	WHITE
	BLACK
	GRAY

References

You may also like...