ProgrammerX ProgrammerX -4 years ago 100
JSON Question

JSONArray printing same values

The JSON object

obj
is inserted into the
JSONArray arr
, but when the Array is printed, the same object is printed for the number of iterations of
ResultSet
.

Can someone tell me what's the mistake?

try {
connection = DriverManager.getConnection(connectionUrl+dbName, userId,password);
statement=connection.createStatement();
statement2=connection.createStatement();
String sql1 ="SELECT * FROM patient_detail where nurseid="+uidd;
resultSet = statement.executeQuery(sql1);
while(resultSet.next())
{
obj.put("fname", resultSet.getString("fname"));
obj.put("lname", resultSet.getString("lname"));
obj.put("pid", resultSet.getString("pid"));
obj.put("gender", resultSet.getString("gender"));
obj.put("dob", resultSet.getString("dob"));
obj.put("appdate", resultSet.getString("appdate"));
obj.put("diseaseid", resultSet.getString("diseaseid"));
list.add(obj);
}

String jsonText1 = JSONValue.toJSONString(list);
connection.close();
}

Answer Source

In the loop you are mutating the same object in each iteration, and then adding the same object to the list. Any change you make in the next iteration to that object is a change to the object you stored in the list. So at the end your list contains n references to the same object.

To solve this, create a new object in each iteration:

try { 
    connection = DriverManager.getConnection(connectionUrl+dbName, userId,password);
    statement=connection.createStatement();
    statement2=connection.createStatement();
    String sql1 ="SELECT * FROM patient_detail where nurseid="+uidd;
    resultSet = statement.executeQuery(sql1);
    while(resultSet.next())
    {
        obj = new JSONObject(); // <----
        obj.put("fname", resultSet.getString("fname"));
        obj.put("lname", resultSet.getString("lname"));
        obj.put("pid", resultSet.getString("pid"));
        obj.put("gender", resultSet.getString("gender"));
        obj.put("dob", resultSet.getString("dob"));
        obj.put("appdate", resultSet.getString("appdate"));
        obj.put("diseaseid", resultSet.getString("diseaseid"));
        list.add(obj);
    }

    String jsonText1 = JSONValue.toJSONString(list);
    connection.close();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download