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>?

1
  • @trololo : The solution here does not give the answer to my question . I just need a simple, direct conversion to List<JSONObject> , not an array . Commented Jul 27, 2015 at 9:44

3 Answers 3

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());
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is there not a method specifically for List<JSONObject> and not ArrayList<JSONObject> ?
@AishwaryaGarg I have updated the answer. List<?> is just an interface.
I get the error that " The method add(org.json.JSONObject) in the type List<JSONObject> is not applicable for the arguments (com.amazonaws.util.json.JSONObject) " upon using the above code.
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());
   } 
} 

2 Comments

Is there not a method specifically for List<JSONObject> and not ArrayList<JSONObject> ?
List is an interface. You can use List<String> listdata instead of ArrayList<String> listdata
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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.