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中文網其他相關文章!