Home >Java >javaTutorial >How do we create a JSON using JsonGenerator in Java?
#JsonGenerator is a base class that defines a public API for writing JSON content. Instances are created using the factory method of the JsonFactory instance. Once we can get the JsonGenerator from the factory instance, we can write the start tag of the JSON object value using the writeStartObject() method, write the field name using the writeFieldName() method, output the string value using the writeString() method, and writeStartArray() The start tag for writing array values using the writeEndObject() method, and the end tag for writing JSON object values using the writeEndObject() method. The Chinese translation of
public abstract class JsonGenerator extends Object implements Closeable, Flushable, Versioned
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()); } }
{ "empid" : "120", "firstName" : "Ravi", "lastName" : "Chandra", "technologies" : [ "SAP", "Java", "Selenium" ] }
The above is the detailed content of How do we create a JSON using JsonGenerator in Java?. For more information, please follow other related articles on the PHP Chinese website!