Allan Jiang
Allan Jiang

Reputation: 11331

Java JSON object to read a list value

I have a JSON response something like this:

{
  "id_list":["123", "456", "789"],
  ...
}

I was wondering what I should do if I want use the JSONObject to read such a id list and to return a List<String> of the ids for example. I did not see there's any method in JSONObject can do such thing (ref: http://www.json.org/javadoc/org/json/JSONObject.html). The most possible one might be the JSONArray, but I don't know if I use JSONArray and turn every value in the list to be an JSONObject, how can I read them without keys.

Thank you

Upvotes: 0

Views: 8963

Answers (1)

Rahul
Rahul

Reputation: 45060

You can iterate through the JSONArray and store each value to the list, and return that.

JSONObject jo = new JSONObject(jsonString); //
JSONArray ja = jo.getJSONArray("id_list"); // get the JSONArray
List<String> keys = new ArrayList<>();

for(int i=0;i<ja.length();i++){
    keys.add(ja.getString(i)); // iterate the JSONArray and extract the keys
}

return keys; // return the list

Upvotes: 2

Related Questions