Json数组未正确生成

Vig*_*ati 2 java json

我编写了java代码,用于从file中生成搜索到的数据的json.但是它没有生成精确的JsonArray.就像是

[{"item":"1617"},{"item":"1617"}]

代替

[{"item":"747"},{"item":"1617"}].

这里1617是从文件中获取的最后一项.

JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();

while (products.readRecord())
{
    String productID = products.get("user");
    int j = Integer.parseInt(productID);
    if(j == userId) {
        itemid = products.get("item");
        jo.put("item",itemid);
        ja.add(jo);
    }
}  

out.println(ja);
products.close();
Run Code Online (Sandbox Code Playgroud)

Sak*_*tel 6

你实际上是在创建一个jSONobject对象来处理两个对象,你不应该在while循环中创建JSONObjects吗?像这样的东西,所以while循环中的每次迭代都会创建一个新的JSONObject并将其添加到JSONArray

JSONArray ja = new JSONArray();

while (products.readRecord())
{
    String productID = products.get("user");
    int j = Integer.parseInt(productID, 10);

    if(j == userId)
    {
         JSONObject jo = new JSONObject();
         itemid = products.get("item");
         jo.put("item", itemid);
         ja.add(jo);
    }

}  

out.println(ja);
products.close();
Run Code Online (Sandbox Code Playgroud)

额外:

我不确定java如何将字符串转换为整数,但我认为你应该在使用parseInt时总是指定基数,所以像'09'这样的字符串不会被视为八进制值并转换为错误的值(至少在javascript中这是真的) :))

Integer.parseInt(productID, 10);

  • +1.更好的是,将实例化移动到if块,避免实例化不必要的对象 (2认同)