Create JSON Using JSONGenerator in Java



JSON is a format for storing and exchanging data. It is easily readable and also easy to parse.

Creating JSON Using Java JsonGenerator

In Java, we can create a JSON object using the JsonGenerator class. JsonGenerator is class in the javax.json.stream package that is used to create JSON data. It provides methods to write JSON objects, arrays, and values.

To use the JsonGenerator class, we need to add the javax.json library to our project. If you are using Maven, add this to your pom.xml file:

<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>

If you are not using Maven, you can download the jar file from here.

Steps 

To create a JSON using the JsonGenerator class in Java, follow these steps:

  • First, import the javax.json library.
  • Then create a JsonGeneratorFactory instance.
  • Then create a JsonGenerator instance using the createGenerator() method of the JsonGeneratorFactory.
  • Now, write JSON data using the writeStartObject(), write(), and writeEnd() methods of the JsonGenerator.
  • Finally, close the JsonGenerator instance.
  • Print the JSON data.

Example

Following is the code to create a JSON using the JsonGenerator class in Java:

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;
import java.io.StringWriter;

public class JsonGeneratorExample {
   public static void main(String[] args) {
      // Create a JsonGeneratorFactory instance
      JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
      // Create a StringWriter to hold the JSON data
      StringWriter stringWriter = new StringWriter();
      // Create a JsonGenerator instance
      JsonGenerator jsonGenerator = factory.createGenerator(stringWriter);
      // Write JSON data
      jsonGenerator.writeStartObject()
                   .write("name", "Ansh")
                   .write("age", 23)
                   .write("city", "Delhi")
                   .writeEnd()
                   .close();
      // Print the JSON data
      System.out.println(stringWriter.toString());
   }
}

Following is the output of the above code:

{"name":"Ansh","age":23,"city":"Delhi"}
Updated on: 2025-05-13T15:43:25+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements