How to create a JSON Array using Object Model in Java?

JavaJSONObject Oriented ProgrammingProgramming

The javax.json.JsonArray interface can represent an immutable JSON array and provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source and also using a static method createArrayBuilder() of javax.json.Json class. We need to import the javax.json package (download javax.json-api.jar file) in order to execute it.

Syntax

public static JsonArrayBuilder createArrayBuilder()

Example

import java.io.*;
import javax.json.*;
import javax.json.JsonObjectBuilder;
public class JsonArrayTest {
   public static void main(String[] args) {
      JsonObjectBuilder builder = Json.createObjectBuilder();
      builder.add("Name", "Raja Ramesh");
      builder.add("Designation", "Java Developer");
      builder.add("Company", "TutorialsPoint");
      JsonArray contactInfo = Json.createArrayBuilder().add(Json.createObjectBuilder().add("email", "raja@gmail.com")).add(Json.createObjectBuilder().add("mobile", "9959984000")).build();
      builder.add("contactInfo", contactInfo);
      JsonObject data = builder.build();
      StringWriter sw = new StringWriter();
      JsonWriter jw = Json.createWriter(sw);
      jw.writeObject(data);
      jw.close();
      System.out.println(sw.toString());
   }
}

Output

{"Name":"Raja Ramesh","Designation":"Java Developer","Company":"TutorialsPoint",
"contactInfo":[{"email":"raja@gmail.com"},{"mobile":"9959984000"}]}
raja
Published on 21-Oct-2019 13:18:50
Advertisements