How can we implement a JSON array using Streaming API in Java?


The JsonGenerator interface can be used to write the JSON data to an output source in a streaming way. We can create or implement a JSON array using the writeStartArray() method of JsonGenerator, this method writes the JSON name/start array character pair within the current object context. The writeStartObject() method writes the JSON start object character, and valid only in an array context and the writeEnd() method writes the end of the current context.

Syntax

JsonGenerator writeStartArray(String name)

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();
      JsonGenerator jsonGen = Json.createGenerator(writer);
      jsonGen.writeStartObject()
             .write("name", "Adithya")
             .write("designation", "Python Developer")
             .write("company", "TutorialsPoint")
             .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());
   }
}

Output

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

Updated on: 18-Feb-2020

638 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements