2

I submit a query from my Java application, which upon running on Elasticsearch server returns the result in the form of a string. I want the result as a list of JSONObject objects. I can convert the string to a JSONObject using JSONObject jsonResponse = new JSONObject(responseString).

Is there any method by which I can get this in the form of a List<JSONObject>?

Armen Michaeli
  • 8,625
  • 8
  • 58
  • 95
Aishwarya Garg
  • 39
  • 2
  • 2
  • 7
  • @trololo : The solution here does not give the answer to my question . I just need a simple, direct conversion to List , not an array . – Aishwarya Garg Jul 27 '15 at 09:44

3 Answers3

5

Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:

List<JSONObject> list = new ArrayList<JSONObject>();
try {
    int i;
    JSONArray array = new JSONArray(string);
    for (i = 0; i < array.length(); i++)
        list.add(array.getJSONObject(i);
} catch (JSONException e) {
    System.out.println(e.getMessage());
}
Victor Dodon
  • 1,796
  • 3
  • 18
  • 27
0

There is an answer of your question: https://stackoverflow.com/a/17037364/1979882

ArrayList<String> listdata = new ArrayList<String>();     
JSONArray jArray = (JSONArray)jsonObject; 
if (jArray != null) { 
   for (int i=0;i<jArray.length();i++){ 
    listdata.add(jArray.get(i).toString());
   } 
} 
Community
  • 1
  • 1
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
0

This method is really easy and works too

try {

    JSONObject jsonObject = new JSONObject(THESTRINGHERE);
    String[] names = JSONObject.getNames(jsonObject);
    JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));

    ArrayList<String> listdata = new ArrayList<String>();     
    JSONArray jArray = (JSONArray)jsonArray; 
    if (jArray != null) { 
       for (int i=0;i<jArray.length();i++){ 
           listdata.add(jArray.get(i).toString());
       } 
    } 
    //  System.out.println(listdata);


} catch (Exception e) {
    System.out.println(e.getMessage());
}
Rich L
  • 1,905
  • 2
  • 19
  • 30