I have got a ResultSet after firing a query. Kindly let me know how i can convert it to a JSON output in JSP.
In the second stage, lets assume that we have got a JSON output like in this link > http://inknpost.com/eshopping/json.jsp
The above file is being accessed by a $.getJSON(); in another file.
Kindly let me know how can i display the "names" and the "departments" in different rows in a page.
String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
Create a reuseable Javabean class which represents one row, a single entity.
public class Category {
private Long id;
private String name;
private String department;
// Add/generate getters/setters/c'tors/equals/hashcode and other boilerplate.
}
Create a reuseable DAO class which maps the ResultSet
to a collection of those Javabeans the usual JDBC way.
public class CategoryDAO {
private static final String SQL_LIST = "SELECT id, name, department FROM category";
// ...
public List<Category> list() throws SQLException {
List<Category> categories = new ArrayList<Category>();
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_LIST);
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
Category category = new Category();
category.setId(resultSet.getLong("id"));
category.setName(resultSet.getString("name"));
category.setDepartment(resultSet.getString("department"));
categories.add(category);
}
}
return categories;
}
// ...
}
Create a servlet class which uses a JSON serializer/deserializer which is able to convert between an arbirary collection of Javabeans and a JSON String, such as Google Gson.
@WebServlet("/categories.json")
public class CategoriesJsonServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Category> categories = categoryDAO.list();
String categoriesJson = new Gson().toJson(categories);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(categoriesJson);
} catch (SQLException e) {
throw new ServletException("DB error", e);
}
}
}
Invoke it by http://localhost:8080/contextname/categories.json
. No, there is no JSP involved. You should not be using JSP for output formats other than HTML.
Finally, in jQuery, just access it the usual $.getJSON()
way.
$('#somebutton').click(function() {
$.getJSON('categories.json', function(categoriesJson) {
var $table = $('<table>').appendTo($('#somediv'));
$.each(categoriesJson, function(index, category) {
$('<tr>').appendTo($table)
.append($('<td>').text(category.id))
.append($('<td>').text(category.name))
.append($('<td>').text(category.department));
});
});
});
To create your json, you can use the google-gson library.
Then, to process your json in jQuery, it depends on your needs, but assuming you want to show them in a table, you could do it the following way:
HTML:
<table id="mytable">
<tr> <th> Name </th> <th> Department </th> </tr>
</table>
Javascript:
$.getJSON("your_url", function(categories){
for(var i=0; i<categories.length; i++){
var name = categories[i].name;
var department = categories[i].department;
$("#mytable").append('<tr><td>'+ name +'</td><td>'+department+'</td></tr>');
}
});
Hope this helps. Cheers
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