Gson Streaming APIs to read and write JSON

Streaming APIs are efficient ways of processing large JSON files or data without loading the entire document into memory. Gson provides JsonReader and JsonWriter classes for JSON streaming.

Gson’s Streaming API

  • JsonWriter – Write JSON as a stream.
  • JsonReader – Read JSON as a stream.

Table of contents:

P.S Tested with Gson 2.10.1

1. Setup Google Gson

Declares gson in the pom.xml.

pom.xml

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>

1. Write JSON String using JsonWriter

The following example uses Gson’s JsonWriter to write JSON to a file named user.json.

JsonWriterExample1.java

package com.mkyong.json.gson.streaming;

import com.google.gson.stream.JsonWriter;

import java.io.FileWriter;
import java.io.IOException;

public class JsonWriterExample1 {

    public static void main(String[] args) {

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

            // pretty print
            writer.setIndent("  ");

            writer.beginObject();                   // {
            writer.name("name").value("mkyong");    // "name" : "mkyong"
            writer.name("age").value(42);           // "age" : 42

            writer.name("messages");                // "messages" :
            writer.beginArray();                    // [
            writer.value(1);                        // 1,
            writer.value(2);                        // 2,
            writer.value(3);                        // 3
            writer.endArray();                      // ]

            writer.endObject();                     // }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Output

user.json

{
  "name": "mkyong",
  "age": 42,
  "messages": [
    1,
    2,
    3
  ]
}

2. Write JSON Array using JsonWriter

The following example uses Gson’s JsonWriter to write a JSON Array to a file named user.json.

JsonWriterExample2.java

package com.mkyong.json.gson.streaming;

import com.google.gson.stream.JsonWriter;

import java.io.FileWriter;
import java.io.IOException;

public class JsonWriterExample2 {

    public static void main(String[] args) {

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

            // pretty print
            writer.setIndent("  ");

            writer.beginArray();                    // [

            writer.beginObject();                   // {

            writer.name("name").value("mkyong");    // "name" : "mkyong"
            writer.name("age").value(42);           // "age" : 42
            writer.name("messages");                // "messages" :
            writer.beginArray();                    // [
            writer.value(1);                        // 1,
            writer.value(2);                        // 2,
            writer.value(3);                        // 3
            writer.endArray();                      // ]

            writer.endObject();                     // }

            writer.beginObject();                   // {

            writer.name("name").value("ah pig");    // "name" : "ah pig"
            writer.name("age").value(20);           // "age" : 20

            writer.name("messages");                // "messages" :
            writer.beginArray();                    // [
            writer.value("a");                        // a,
            writer.value("b");                        // b,
            writer.value("c");                        // c
            writer.endArray();                      // ]

            writer.endObject();                     // }

            writer.endArray();                      // [

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Output

user.json

[
  {
    "name": "mkyong",
    "age": 42,
    "messages": [
      1,
      2,
      3
    ]
  },
  {
    "name": "ah pig",
    "age": 20,
    "messages": [
      "a",
      "b",
      "c"
    ]
  }
]

3. Read JSON String using JsonReader

The following example uses Gson’s JsonReader to read JSON from a file named user.json and print out the JSON values.

A JSON object.

user.json

{
  "name": "mkyong",
  "age": 42,
  "messages": [
    1,
    2,
    3
  ]
}
JsonReaderExample1.java

package com.mkyong.json.gson.streaming;

import com.google.gson.stream.JsonReader;

import java.io.FileReader;
import java.io.IOException;

public class JsonReaderExample1 {

    public static void main(String[] args) {

        try (JsonReader reader = new JsonReader(new FileReader("user.json"))) {

            reader.beginObject();

            while (reader.hasNext()) {

                String name = reader.nextName();

                switch (name) {
                    case "name" -> System.out.println(reader.nextString());
                    case "age" -> System.out.println(reader.nextInt());
                    case "messages" -> {
                        // read array
                        reader.beginArray();
                        while (reader.hasNext()) {
                            System.out.println(reader.nextString());
                        }
                        reader.endArray();
                    }
                    default -> reader.skipValue(); // skip others
                }
            }

            reader.endObject();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Output


mkyong
42
1
2
3

4. Read JSON Array using JsonReader

The following example uses Gson’s JsonReader to read JSON Array from a file named user.json and print out the JSON values.

A JSON Array.

user.json

[
  {
    "name": "mkyong",
    "age": 42,
    "messages": [
      1,
      2,
      3
    ]
  },
  {
    "name": "ah pig",
    "age": 20,
    "messages": [
      "a",
      "b",
      "c"
    ]
  }
]
JsonReaderExample2.java

package com.mkyong.json.gson.streaming;

import com.google.gson.stream.JsonReader;

import java.io.FileReader;
import java.io.IOException;

public class JsonReaderExample2 {

    public static void main(String[] args) {

        try (JsonReader reader = new JsonReader(new FileReader("user.json"))) {

            reader.beginArray(); // this is an json array
            while (reader.hasNext()) {

                reader.beginObject();

                while (reader.hasNext()) {

                    String name = reader.nextName();

                    switch (name) {
                        case "name" -> System.out.println(reader.nextString());
                        case "age" -> System.out.println(reader.nextInt());
                        case "messages" -> {
                            // read array
                            reader.beginArray();
                            while (reader.hasNext()) {
                                System.out.println(reader.nextString());
                            }
                            reader.endArray();
                        }
                        default -> reader.skipValue(); // skip others
                    }
                }
                reader.endObject();
            }

            reader.endArray();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Output


mkyong
42
1
2
3
ah pig
20
a
b
c

5. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd gson

6. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments