Reputation: 39
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>
?
Upvotes: 2
Views: 27752
Reputation: 41
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());
}
Upvotes: 0
Reputation: 1864
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());
}
Upvotes: 5
Reputation: 27211
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());
}
}
Upvotes: 0