Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add JsonObjects to javax.json.JsonArray Using Loop (dynamically)

Tags:

java

json

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.

like image 236
eMad Avatar asked May 26 '14 13:05

eMad


2 Answers

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();
like image 170
Albert Sadowski Avatar answered Oct 15 '22 04:10

Albert Sadowski


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();
like image 20
Mohit Aggarwal Avatar answered Oct 15 '22 05:10

Mohit Aggarwal