Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Create JSON Array Using Object Model in Java



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", "[email protected]")).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":"[email protected]"},{"mobile":"9959984000"}]}
Updated on: 2020-07-07T07:09:51+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements