Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json Array not properly generated

Tags:

java

json

I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like

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

instead of

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

Here 1617 is last item which is fetched from file.

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();
like image 320
Vignesh Prajapati Avatar asked Mar 15 '26 04:03

Vignesh Prajapati


2 Answers

you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to 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();

Extra:

i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))

Integer.parseInt(productID, 10);

like image 118
Saket Patel Avatar answered Mar 16 '26 18:03

Saket Patel


You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.

like image 20
Guillaume Polet Avatar answered Mar 16 '26 18:03

Guillaume Polet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!