10

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.

2
  • Well obviously the for loop is certainly not an object and you cannot call build on it. You would want to call build on jarr at the end of the iteration. Also, i < posts[i] probably doesn't make any sense. Commented May 26, 2014 at 13:32
  • posts and ids are String array Containing the Data to be added. Commented May 26, 2014 at 13:34

2 Answers 2

19

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! This has saved me hours of frustration: turned out I needed to add the JsonObject before build().
4

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();

2 Comments

Your first line desn't compile for me. The first word needs to be JsonArrayBuilder. Then it should be called builder, not jarr.
The concept is good, but the naming convention is whacked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.