Open In App

How to Create and Close JsonGenerator?

Last Updated : 08 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

To begin with, What is JSON? JSON stands for JavaScript Object Notation . It’s a data exchange format that is used between server and client. An example of JSON data:

{
"name" : "Sonali Singh",
"age": 40,
"address" : {
"state": "Texas",
"city": "Houston"
            }
}

JSONGenerator is an interface that writes JSON data to the output source in a streaming way. In order to create an instance of JSONGenerator, we need to use the JSONFactory instance. 

JsonFactory factory = new JsonFactory();

This factory instance has a method called CreateGenerator that will create the JSONGenerator.

JsonGenerator generator = factory.createGenerator(new File("test.json"));

createGenerator takes in the destination where we want the JSON to be written to as the first parameter. If we use bytestream as the first parameter, we can also optionally specify the CharSet

createGenerator(OutputStream out, Charset charset)

Now we can start writing the JSON into our stream. The first method to be called from the generator object is writeStartObject() for writing objects or writeStartArray() for writing array after which we can specify the key and value names. After we finish writing the JSON, we specify the writeEnd() function which marks the end of our JSON data.

Example

writeStartObject:

generator.writeStartObject().write("name": "Sonali Singh").write("age":40).writeEnd().close()
The JSON generated is {"name" : "Sonali Singh","age": 40,}

writeStartArray:

generator
    .writeStartObject().write("name", "Sonali Singh").write("age", 25)
        .writeStartArray("education")
            .writeStartObject()
                .write("type", "college")
                .write("course", "B.Com")
            .writeEnd()
            .writeStartObject()
                .write("type", "Higher Secondary")
                .write("course", "Commerce")
            .writeEnd()
        .writeEnd()
    .writeEnd();
generator.close();
The JSON generated is 
{"name": :Sonali Singh", "age" : 25,
"education" : [ {"type", "college", "course", "B.Com},
                {"type", "Higher Secondary", "course", "Commerce"}
                ]
}

In the end, we call the .close() method of the Generator. This method frees the resources by closing the corresponding output stream.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads