2

I am fetching details from a database table which contains 3 rows in JAVA. I am using JSONarray and JSONObject as follows

JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
JSONArray ja=new JSONArray();

The data from table is put to the jsonObject as follows for each one:

String qry="select * from details";
ResultSet res = select .executeQuery(qry);
while(res.next){

String Name=res.getString("name");
.
.

jsonObject.put("Name", Name);

.

.

ja.put(jsonObject);

}



mainjsonObject.put("PERSONAL DETAILS",ja);

i should get the output json as follows:

{
"PERSONAL DETAILS": [
    {
      " name": "abc",
      "age": "4",
      "gender": "F",
      "Place": "abc1"
    },
    {
      " name": "xyz",
      "age": "3",
      "gender": "M",
      "Place": "abc2"
    }


]

}

But am getting same values in both like below:

{

"PERSONAL DETAILS": [

    {

     " name": "abc",

     "age": "4",

     "gender": "F",

      "Place": "abc1"

    },

    {

   " name": "abc",

   "age": "4",

   "gender": "F",

   "Place": "abc1"

    }


]

}

Please help me with a solution. I need to get all the values from the tables as an array in JSON format

2 Answers 2

3

you need to create new JSONObject in your loop otherwise the last record will be shown everywhere

while(res.next()){

    String Name=res.getString("name");
    jsonObject = new JSONObject();
    // ^^^^^^^^
    jsonObject.put("Name", res.getString(1));
    jsonObject.put("age", res.getString(2));
    jsonObject.put("gender", res.getString(3));
    jsonObject.put("Place", res.getString(4));
    ja.put(jsonObject);
 }
Sign up to request clarification or add additional context in comments.

6 Comments

You beat me to it :p Except that there are some pieces of code missing from your example :)
Thanks for ur reply @Pavneet_Singh. But can u pls cleary specify how to do it in the above one. Wat value to be given to the newly created JSONObject inside the loop
@Leeza as shown , get value from your resultset and put it inside jsonObject reference
@fge i guess you are talking about next() , copied the code from OP to save some time :P
i am glad that we (me & @fge & SO) could help , happy coding
|
2

The problem is that you are reusing the same JSONObject over and over. And this is basically a Map.

What you need to do is create a new JSONObject instance and put it in the array for each iteration:

JSONObject obj;
while (rs.next()) {
    obj = new JSONObject();
    // fill in obj
    ja.put(obj);
}

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.