Java JsonGenerator-class And Method Code Example


Here's an example of using the JsonGenerator class from the Apache Commons IO library to write a JSON object to a file:

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;

public class JsonExample {
    public static void main(String[] args) throws IOException {
        JsonFactory jsonFactory = new JsonFactory();
        File jsonFile = new File("example.json");

        try (JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(FileUtils.openOutputStream(jsonFile))) {
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("name", "John Doe");
            jsonGenerator.writeNumberField("age", 30);
            jsonGenerator.writeBooleanField("isEmployed", true);
            jsonGenerator.writeEndObject();
        }
    }
}

In this example, we first create a JsonFactory object, which we use to create a JsonGenerator for the output file. We then use the JsonGenerator to write a JSON object with fields for a name, age, and employment status. The writeStartObject and writeEndObject methods are used to start and end the JSON object, respectively, and the writeStringField, writeNumberField, and writeBooleanField methods are used to add fields to the object.

You would also need to add the jackson-databind dependency.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.3</version>
</dependency>

It will generate the following output in a file named example.json:

{ "name": "John Doe", "age": 30, "isEmployed": true }

Please note that this example writes the json to a file, you can also write the json to an output stream.