In my project, I used JSON to pass readed data from database to client side.In this code I put JSONObject in to JSONArray and pass to client side.
This my code for JsonProcessing.java
servlet:
JSONObject obj = new JSONObject();
JSONArray objarr = new JSONArray();
//read from DB
sql = "SELECT id, name FROM test";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
String first = rs.getString("name");
obj.put("name", first);
obj.put("id", id);
objarr.add(obj);
System.out.print("\nobj: "+obj);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(objarr);
out.flush();
And this is my javascript code:
$.ajax({
url : "/test/JsonProcessing",
type : "get",
data : {
id : 30
},
success : function(info) {
//alert(info.name);
console.log(info);
for (var i = 0; i < info.length; i++) {
alert(i + ": " + info[i].name + " " + info[i].id);
}
// data: return data from server
},
error : function() {
alert('Faild');
// if fails
}
});
I don't know why I take duplicate same result in alert ?
Update your java code as follow:
JSONArray objarr = new JSONArray();
//read from DB
sql = "SELECT id, name FROM test";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
JSONObject obj = new JSONObject(); // updated
// Retrieve by column name
int id = rs.getInt("id");
String first = rs.getString("name");
// Display values
System.out.print("\nID: " + id);
System.out.print(", Name: " + first);
obj.put("name", first);
obj.put("id", id);
objarr.add(obj);
System.out.print("\nobj: "+obj);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(objarr);
out.flush();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With