Writing JSON Data in a streaming way

This post explains how to write json data to a file using JsonGenerator. The previous post explains the same using JsonWriter. The difference is that to use JsonWriter we need to build the entire object (which represents json data) in memory before writing to a file. Whereas with JsonGenerator we dont need to build the entire object. The code explains how to write the below json data


{
    "firstName": "Duke",
    "lastName": "Java",
    "age": 18,
    "streetAddress": "100 Internet Dr",
    "city": "JavaTown",
    "state": "JA",
    "postalCode": "12345",
    "phoneNumbers": [
        { "Mobile": "111-111-1111" },
        { "Home": "222-222-2222" }
    ]
}

Code


package objectmodel;

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

import javax.json.Json;
import javax.json.stream.JsonGenerator;

public class Example7 {
    public static void main(String[] args) {
        try(FileWriter fw = new FileWriter("E:\\Projects\\JavaProjects\\JavaJSONProject\\jsondata4.txt");
        JsonGenerator jsonGenerator = Json.createGenerator(fw);) {
            jsonGenerator.writeStartObject(); //Writes the character '{'
            jsonGenerator.write("firstName","Duke");
            jsonGenerator.write("lastName","Duke");
            jsonGenerator.write("age",18);
            jsonGenerator.write("streetAddress","100 Internet Dr");
            jsonGenerator.write("city","JavaTown");
            jsonGenerator.write("state","JA");
            jsonGenerator.write("postalCode","12345");

            jsonGenerator.writeStartArray("phoneNumbers"); //Writes the character '['
            jsonGenerator.writeStartObject();
            jsonGenerator.write("Mobile","111-111-1111");
            jsonGenerator.writeEnd();
            jsonGenerator.writeStartObject();
            jsonGenerator.write("Home","222-222-2222");
            jsonGenerator.writeEnd();
            jsonGenerator.writeEnd(); //Writes the character ']'

            jsonGenerator.writeEnd(); //Writes the character '}'
        } catch(IOException excep){
            excep.printStackTrace();
        }
    }
}

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s