Home > Java > javaTutorial > How do we create a JSON using JsonGenerator in Java?

How do we create a JSON using JsonGenerator in Java?

WBOY
Release: 2023-08-23 19:01:09
forward
1036 people have browsed it

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

Grammar

public abstract class JsonGenerator extends Object implements Closeable, Flushable, Versioned
Copy after login

Example

is:

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());
   }
}
Copy after login

Output

{
   "empid" : "120",
   "firstName" : "Ravi",
   "lastName" : "Chandra",
   "technologies" : [ "SAP", "Java", "Selenium" ]
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template