In this article, you will learn how to read and write JSON as a stream by using the Gson open-source library.

Streaming is the fastest and most efficient way of processing large JSON files. Gson provides two class for streaming JSON data:

  1. JsonWriter — Write JSON data as a stream
  2. JsonReader — Read JSON data as a stream

Write JSON as a Stream

The following example demonstrates how to use the JsonWriter class to write JSON data as a stream of tokens to a file:

try {
    // create a writer
    Writer fileWriter = Files.newBufferedWriter(Paths.get("user.json"));

    // create `JsonWriter` instance
    JsonWriter writer= new JsonWriter(fileWriter);

    // write JSON data
    writer.beginObject();
    writer.name("name").value("John Doe");
    writer.name("email").value("john.doe@example.com");
    writer.name("admin").value(false);

    writer.name("roles");
    writer.beginArray();
    writer.value("Member");
    writer.value("Admin");
    writer.endArray();

    writer.endObject();

    // close the writer
    fileWriter.close();

} catch (Exception ex) {
    ex.printStackTrace();
}

Here is how the user.json file looks like:

{"name":"John Doe","email":"john.doe@example.com","admin":false,"roles":["Member","Admin"]}

Read JSON as a Stream

Reading JSON data as a stream is a bit tricky. This is because every single string is considered as an individual token. Here is an example that uses the JsonReader class to stream the contents of user.json file:

try {
    // create a reader
    Reader fileReader = Files.newBufferedReader(Paths.get("user.json"));

    // create `JsonReader` instance
    JsonReader reader = new JsonReader(fileReader);

    // read data
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        switch (name) {
            case "name":
            case "email":
                System.out.println(reader.nextString());
                break;
            case "admin":
                System.out.println(reader.nextBoolean());
                break;
            case "roles":
                reader.beginArray();
                while (reader.hasNext()) {
                    System.out.println(reader.nextString());
                }
                reader.endArray();
                break;
            default:
                // skip everything else
                reader.skipValue();
                break;
        }
    }
    reader.endObject();

    // close the reader
    fileReader.close();

} catch (Exception ex) {
    ex.printStackTrace();
}

You should see the following output printed on the console:

John Doe
john.doe@example.com
false
Member
Admin

For more Gson examples, check out the How to read and write JSON using Gson in Java tutorial.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.