Read and write JSON as a stream using Gson

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.