0

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

1 Answer 1

2

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

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.