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.
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();
You need to finish building your JsonObjectBuilder at the end of each iteration to make it work
JsonArrayBuilder jarr = Json.createArrayBuilder();
for (int i = 0; i < posts[i]; i++)
{
jarr.add(Json.createObjectBuilder()
.add("post", posts[i])
.add("id", ids[i]).build());
}
jarr.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With