简体   繁体   中英

Need Json results in a Table Format

I am getting results in json format, i need to display my results in a table format, Getting a input from html, executing it servlet program, the sparql query shows result in Json format, can anybody help me in showing the result in table format?

response.setContentType("json-comment-filtered");
response.setHeader("Cache-Control","nocache");

OutputStream out = response.getOutputStream();
//  ResultSetFormatter.outputAsXML(out, results);
System.out.println("called");
out.flush();
JSONOutput jOut = new JSONOutput();
jOut.format(out, results);

soon the query is executed, the set of code is executed and results are displayed in json format, so can anybody help me out in way that I can get results in table format.

Your actual problem is that you don't know how to process the JSON string in the client side. I strongly suggest to use jQuery for this since this simplifies DOM manipulation a lot. I suggest to go through their tutorials or go get a decent book on the subject.

For the jQuery + JSON + Servlet + HTML table mix, I've posted similar answers before here and here with code examples how to populate a table with help of Google Gson and a Servlet, you may find it useful. I'll copypaste from one of them.

Here are the Servlet and the Javabean:

public class JsonServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Data> list = dataDAO.list();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(new Gson().toJson(list));
    }
}

public class Data {
    private Long id;
    private String name;
    private Integer value;
    // Add/generate getters/setters.
}

The JsonServlet (you may name it whatever you want, this is just a basic example) should be mapped in web.xml on a known url-pattern , let's use /json in this example. The class Data just represents one row of your HTML table (and the database table).

Now, here's how you can load a table with help of jQuery.getJSON :

$.getJSON("http://example.com/json", function(list) {
    var table = $('#tableid');
    $.each(list, function(index, data) {
        $('<tr>').appendTo(table)
            .append($('<td>').text(data.id))
            .append($('<td>').text(data.name))
            .append($('<td>').text(data.value));
    });
});

The tableid of course denotes the id of the HTML <table> element in question.

<table id="tableId"></table>

That should be it. After all it's fairly simple, believe me. Good luck.

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