Leeza
Leeza

Reputation: 127

How to Create a JSONArray using JSONObject with all values from a database table in java

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

Upvotes: 2

Views: 661

Answers (2)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

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

Upvotes: 3

fge
fge

Reputation: 121710

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

Upvotes: 2

Related Questions