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.
forloop is certainly not an object and you cannot callbuildon it. You would want to call build onjarrat the end of the iteration. Also,i < posts[i]probably doesn't make any sense.