How can we create a JSON using JsonGenerator in Java?


The JsonGenerator is a base class that defines public API for writing JSON content. The instances are created using factory methods of a JsonFactory instance. Once we can get the JsonGenerator from factory instance then use the writeStartObject() for writing starting marker of a JSON Object value, writeFieldName() method for writing a field name, writeString() method for outputting a String value, writeStartArray() method for writing starting marker of a Array value and writeEndObject() method for writing closing marker of a JSON Object value.

Syntax

public abstract class JsonGenerator extends Object implements Closeable, Flushable, Versioned

Example

import java.io.*;
import com.fasterxml.jackson.core.*;

public class JsonGeneratorTest {  
   public static void main(String args[]) throws IOException {
      JsonFactory factory = new JsonFactory();
      StringWriter jsonObjectWriter = new StringWriter();
      JsonGenerator generator = factory.createGenerator(jsonObjectWriter);
      generator.useDefaultPrettyPrinter(); // pretty print JSON
      generator.writeStartObject();

      generator.writeFieldName("empid");
      generator.writeString("120");
      generator.writeFieldName("firstName");
      generator.writeString("Ravi");
      generator.writeFieldName("lastName");
      generator.writeString("Chandra");
      generator.writeFieldName("technologies");
      generator.writeStartArray();
      generator.writeString("SAP");
      generator.writeString("Java");
      generator.writeString("Selenium");
      generator.writeEndArray();

      generator.writeEndObject();
      generator.close(); // to close the generator

      System.out.println(jsonObjectWriter.toString());
   }
}

Output

{
   "empid" : "120",
   "firstName" : "Ravi",
   "lastName" : "Chandra",
   "technologies" : [ "SAP", "Java", "Selenium" ]
}
raja
Published on 11-Oct-2019 12:38:21
Advertisements