2

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

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1. Even better, move the instantiation to the if-block, avoiding to instantiate unnecessary objects
3

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.

Comments

2

Place JSONObject jo = new JSONObject(); inside the loop:

while (products.readRecord())
{
  JSONObject jo = new JSONObject();
  String productID = products.get("user");
  int j = Integer.parseInt(productID);
  // etc

}

Comments

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.