How to add JsonObjects to javax.json.JsonArray Using Loop (dynamically)
java, json
Solution
What you've posted is not written in Java.
First get the builder:
JsonArrayBuilder builder = Json.createArrayBuilder();
then iterate and add objects in the loop:
for(...) {
builder.add(/*values*/);
}
finally get the JsonArray:
JsonArray arr = builder.build();
Problem
To Add Objects to a JsonArray, following sample code is given on Oracle.com. ``` JsonArray value = Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number", "212 555-1234")) .add(Json.createObjectBuilder() .add("type", "fax") .add("number", "646 555-4567")) .build(); ``` Actually I've a Servlet that would read data from the database and depending on the number of rows retrieved, it would add the data as JsonObject to JsonArray. For that all I could think was using loops to add JsonObject to JsonArray but it doesn't work. Here's what I was doing. Here, ``` //Not working JsonArray jarr = Json.createArrayBuilder() for (int i = 0; i < posts[i]; i++) { .add(Json.createObjectBuilder() .add("post", posts[i]) .add("id", ids[i])) } .build(); ``` Its my first time using Java Json APIs. What's the right way to add objects dynamically to JsonArray.