JsonGenerator 接口可用于写入JSON数据到一个输出源以流方式。我们可以创建或实现使用JSON数组writeStartArray()的方法JsonGenerator,这种方法写入JSON名称/当前对象范围内启动数组字符对。 writeStartObject()方法只在数组上下文写入JSON起始对象字符,并有效和writeEnd()方法写入当前上下文的末端。
JsonGenerator writeStartArray(String name)
import java.io.*; import javax.json.*; import javax.json.stream.*; public class JsonGeneratorTest { public static void main(String[] args) throws Exception { StringWriter writer = new StringWriter(); JsonGenerator jsonGen = Json.createGenerator(writer); jsonGen.writeStartObject() .write("name", "Adithya") .write("designation", "Python Developer") .write("company", "nhooo") .writeStartArray("personal details") .writeStartObject() .write("email", "adithya@gmail.com") .writeEnd() .writeStartObject() .write("contact", "9959927000") .writeEnd() // end of object .writeEnd() // end of an array .writeEnd(); // end of main object jsonGen.close(); System.out.println(writer.toString()); } }
输出结果
{"name":"Adithya","designation":"Python Developer","company":"nhooo","personal details":[{"email":"adithya@gmail.com"},{"contact":"9959927000"}]}