简体   繁体   English

如何将JsonObjects添加到javax.json.JsonArray使用循环(动态)

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

To Add Objects to a JsonArray, following sample code is given on Oracle.com. 要将对象添加到JsonArray,请在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. 实际上我有一个从数据库读取数据的Servlet,根据检索的行数,它会将数据作为JsonObject添加到JsonArray。 For that all I could think was using loops to add JsonObject to JsonArray but it doesn't work. 为此我可以想到的是使用循环将JsonObject添加到JsonArray但它不起作用。 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. 这是我第一次使用Java Json API。 What's the right way to add objects dynamically to JsonArray. 将对象动态添加到JsonArray的正确方法是什么。

What you've posted is not written in Java. 您发布的内容不是用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:

JsonArray arr = builder.build();

You need to finish building your JsonObjectBuilder at the end of each iteration to make it work 您需要在每次迭代结束时完成构建JsonObjectBuilder以使其工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM