首頁  >  文章  >  Java  >  我們如何在Java中使用流API實作JSON數組?

我們如何在Java中使用流API實作JSON數組?

WBOY
WBOY轉載
2023-09-19 18:01:06652瀏覽

我們如何在Java中使用流API實作JSON數組?

JsonGenerator介面可用於以串流方式將 JSON 資料寫入輸出來源。我們可以使用JsonGeneratorwriteStartArray()方法來建立或實作一個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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除