Reputation: 187
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 want to parse the data and see data in an arraylist format like:
{ID:"123", "Name":"ABC_123"}
{ID:"124", "Name":"ABC_678"}
etc...
Any idea on how I can achieve this either from the client side or from server? Please advice.. Thanks
Upvotes: 0
Views: 273
Reputation: 27476
You should create an ArrayList
of HashMap
s before the loop, and add the data there.
Like this
...rest of your code...
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (int i = 0 ; i < hitsArray.length(); i++) {
JSONObject jObject = hitsArray.getJSONObject(i);
Map<String, String> data = new HashMap<String, String>();
JSONObject source = jObject.get("_source");
Iterator<String> it = source.keys();
while (it.hasNext()) {
String key = it.next();
data.put(key, source.getString(key));
}
list.add(data);
}
request.setAttribute("jsonObject", list);
... rest of your code...
Updated code for the jettison, but I would recommend to switch to javax.json;
Upvotes: 0
Reputation: 1
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);
Upvotes: 1