我们如何使用Java中的JsonGenerator创建一个JSON呢?

语法

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

输出

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

以上就是我们如何使用Java中的JsonGenerator创建一个JSON呢?的详细内容,更多请关注其它相关文章!