简体   繁体   中英

Convert JSONObject to List<JSONObject> or a String to List<JSONObject>

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

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());
}

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());
   } 
} 

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM