JsonGenerator接口可用于以流式传输方式将 JSON 数据写入输出源。我们可以使用JsonGenerator的writeStartArray()方法创建或实现一个JSON数组,该方法在当前对象上下文中写入JSON名称/起始数组字符对。 writeStartObject() 方法写入 JSON 起始对象字符,仅在数组上下文中有效,writeEnd() 方法写入当前上下文的结尾。
<strong>JsonGenerator writeStartArray(String name)</strong>
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(); <strong>JsonGenerator </strong>jsonGen = <strong>Json.createGenerator</strong>(writer); jsonGen.<strong>writeStartObject()</strong> .<strong>write</strong>("name", "Adithya") .<strong>write</strong>("designation", "Python Developer") .<strong>write</strong>("company", "TutorialsPoint") .<strong>writeStartArray</strong>("personal details") .<strong>writeStartObject()</strong> .<strong>write</strong>("email", "adithya@gmail.com") .<strong>writeEnd()</strong> .<strong>writeStartObject()</strong> .<strong>write</strong>("contact", "9959927000") .<strong>writeEnd() // end of object</strong> .<strong>writeEnd() // end of an array</strong> .<strong>writeEnd()</strong>; // <strong>end of main object</strong> jsonGen.close(); System.out.println(writer.toString()); } }
<strong>{"name":"Adithya","designation":"Python Developer","company":"TutorialsPoint","personal details":[{"email":"adithya@gmail.com"},{"contact":"9959927000"}]}</strong>
以上是我们如何在Java中使用流API实现JSON数组?的详细内容。更多信息请关注PHP中文网其他相关文章!