Writing JSON Data using JsonWriter

This post explains how to write json data to a file using JsonWriter. With JsonWriter we dont need to build the entire object in memory. The code explains how to write the below json data


[
        {
                "id": 1,
                "text": "text1",
                "array": null
        },
        {
                "id": 2,
                "text": "text2!",
                "array": [
                        50.454722,
                        -104.606667
                ]
        }
]

The json data shows we are creating an array of two objects. Each object has 3 properties id, text, and array.

Below is the complete java code

Main Code


1  import java.io.File;
2  import java.io.FileWriter;
3  import java.io.IOException;
4  
5  import com.google.gson.stream.JsonWriter;
6  
7  public class GsonDemo4 {
8   public static void main(String[] args) throws IOException {
9       File file = new File("jsondata1.json");
10      FileWriter fw = new FileWriter(file);
11      JsonWriter jw = new JsonWriter(fw);
12      jw.setIndent("        ");
13      jw.beginArray();
14          jw.beginObject();
15              jw.name("id").value(1);
16              jw.name("text").value("text1");
17              jw.name("array").nullValue();
18          jw.endObject();
19          jw.beginObject();
20              jw.name("id").value(2);
21              jw.name("text").value("text2!");
22              jw.name("array");
23              jw.beginArray();
24                  jw.value(50.454722);
25                  jw.value(-104.606667);
26              jw.endArray();
27          jw.endObject();
28      jw.endArray();
29      jw.close();
30  }
31 }

In the above code, at line 12, I set the indentation string to be repeated for each level of indentation.

At line 13, beginArray method marks the start of the array and sends “[” character to the output. This has to accompained by corresponding endArray method (refer to line 28). The endArray method marks the end of the array and sends “]” character to output.

At line 14 and 19, we mark the beginning of the object by calling the method beginObject. This will send “{” to the output. This has to be accompained by corresponding
endObject method (refer to line 18 and 27). The endObject method marks the end of the object and sends “}” to the output.

Next we add properties of the object by using name method (used to set property name) and value method (used to set property value).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s