Sweet Sweet - 7 months ago 17
HTML Question

How to extract key:value from html

I have the following String data that is send from a servlet to the index page.

{ "hits" : {"hits" : [ { "_source":{"ID":"123","Status":"false","Name":"ABC_123","Date":"2010-08-16T11:07:48"} }, { "_source":{"ID":"124","Status":"false","Name":"ABC_678","Date":"2010-08-16T12:00:12"} }, { "_source":{"ID":"125","Status":"true","Name":"FGH_122","Date":"2010-08-16T12:01:48"} }, { "_source":{"ID":"126","Status":"false","Name":"TYT_333","Date":"2010-08-16T12:06:48"} }, { "_source":{"ID":"127","Status":"false","Name":"CVF_230","Date":"2010-08-16T12:07:18"} }, { "_source":{"ID":"128","Status":"true","Name":"AWE_101","Date":"2010-08-16T12:03:48"} }, { "_source":{"ID":"129","Status":"true","Name":"WEC_299","Date":"2010-08-16T12:07:29"} } ] }}


I am getting the value using this line of code in index.html:

<%
String json = request.getAttribute("jsonObject").toString();
%>

<body>
<%= json %>
</body>


I want to parse the data and see data in an arraylist format like:

{ID:"123", "Name":"ABC_123"}
{ID:"124", "Name":"ABC_678"}


etc...

I tried the following from the servlet:

try {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject jsonObj = new JSONObject(jsonString.toString());

JSONObject hitsObj = jsonObj.getJSONObject("hits");
JSONArray hitsArray = hitsObj.getJSONArray("hits");

for (int i = 0 ; i < hitsArray.length(); i++) {
JSONObject jObject = hitsArray.getJSONObject(i);
request.setAttribute("jsonObject", jObject.get("_source"));
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
out.flush();
out.close();
} catch (JSONException e) {
e.printStackTrace();
}


But this is returing just one row in the index.html page.

Any idea on how I can achieve this either from the client side or from server? Please advice.. Thanks

Answer

Create a new array and add objects to it before you return them to the JSP.

JSONArray arr = new JSONArray();
for (int i = 0 ; i < hitsArray.length(); i++) {
    JSONObject jObject = hitsArray.getJSONObject(i);
    arr.put(jObject.get("_source"));         
}    

request.setAttribute("jsonObject", arr);
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);