Main Tutorials

Gson – Read and write JSON as a stream

Since Gson version 1.6, two new classes JsonReader and JsonWriter are introduced to provide streaming processing on JSON data. Read this Gson streaming documentation to understand what are the benefits of using it.

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

1. JsonWriter

GsonExample1.java

package com.mkyong;

import com.google.gson.stream.JsonWriter;

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

public class GsonExample1 {

    public static void main(String[] args) {

        try (JsonWriter writer = new JsonWriter(new FileWriter("c:\\projects\\user.json"))) {

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

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

            writer.endObject();                     // }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output

c:\\projects\\user.json

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

2. JsonReader

Token
In streaming mode, every JSON data consider as an individual token. When you use JsonReader to process it, each token will be processed sequentially. For example,


{
	"url":"www.mkyong.com"
}
  • Token 1 = {
  • Token 2 = url
  • Token 3 = www.mkyong.com
  • Token 4 = }
GsonExample2.java

package com.mkyong;

import com.google.gson.stream.JsonReader;

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

public class GsonExample2 {

    public static void main(String[] args) {

        try (JsonReader reader = new JsonReader(new FileReader("c:\\projects\\user.json"))) {

            reader.beginObject();

            while (reader.hasNext()) {

                String name = reader.nextName();

                if (name.equals("name")) {

                    System.out.println(reader.nextString());

                } else if (name.equals("age")) {

                    System.out.println(reader.nextInt());

                } else if (name.equals("messages")) {

                    // read array
                    reader.beginArray();

                    while (reader.hasNext()) {
                        System.out.println(reader.nextString());
                    }

                    reader.endArray();

                } else {
                    reader.skipValue(); //avoid some unhandle events
                }
            }

            reader.endObject();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output


mkyong
29
msg 1
msg 2
msg 3
Note
Read more Gson examples

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
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Jesz
9 years ago

Hi, thanks for your example, it was very useful for me, but i have a question..
How can i edit a node in a json file????

GM
10 years ago

how can i read the json file from an URL?

Flozza
11 years ago

Thanks !

aka
11 years ago

why is it so slow – in compartion to OutputStream which has write(char[]) operation it is 5 times slower? if in test I do not use write(char[]), only write(int) this gives me 15-20% slower, but because there is not bulk write – it is very slow.