简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM