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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23871265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:44:34  来源:igfitidea点击:

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

javajson

提问by eMad

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. 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,

实际上,我有一个 Servlet 可以从数据库中读取数据,并根据检索到的行数,将数据作为 JsonObject 添加到 JsonArray。为此,我所能想到的就是使用循环将 JsonObject 添加到 JsonArray 但它不起作用。这就是我正在做的。这里,

//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.

这是我第一次使用 Java Json API。将对象动态添加到 JsonArray 的正确方法是什么?

采纳答案by Albert Sadowski

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

回答by Mohit Aggarwal

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