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

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

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

Writing 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 what the user.json file looks like:

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

Reading JSON as a stream

Reading JSON data as a stream is a bit tricky. This is because every single string is considered an individual token. Here is an example that uses the JsonReader class to stream the contents of the 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 me on Twitter and LinkedIn. You can also subscribe to RSS Feed.