0

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

Sweet
  • 187
  • 3
  • 15
  • I think it will much simpler if your accessing your json obj in client side JS. http://stackoverflow.com/questions/35629621/calling-java-method-from-html-without-using-a-servlet/35632063#35632063.in your code snippet i think u miss the `Iterator` try this sample.http://stackoverflow.com/questions/5338943/read-json-string-in-servlet – gihan-maduranga Apr 16 '16 at 06:41

2 Answers2

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);
Roman C
  • 49,761
  • 33
  • 66
  • 176
0

You should create an ArrayList of HashMaps 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;

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115