Home  >  Article  >  Java  >  How can we implement JSON array using streaming API in Java?

How can we implement JSON array using streaming API in Java?

WBOY
WBOYforward
2023-09-19 18:01:06652browse

How can we implement JSON array using streaming API in Java?

The JsonGenerator interface can be used to stream JSON data to an output source. We can create or implement a JSON array using the JsonGenerator's writeStartArray() method, which writes a JSON name/start array character pair in the current object context. writeStartObject() The method writes the JSON starting object character, which is only valid in array context. The writeEnd() method writes the end of the current context.

Syntax

<strong>JsonGenerator writeStartArray(String name)</strong>

Example

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

Output

<strong>{"name":"Adithya","designation":"Python Developer","company":"TutorialsPoint","personal details":[{"email":"adithya@gmail.com"},{"contact":"9959927000"}]}</strong>

The above is the detailed content of How can we implement JSON array using streaming API in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete