Parse simple JSON Array without key

Zookey picture Zookey · Apr 30, 2014 · Viewed 29.8k times · Source

I need help with parsing simple JSONArray like this:

{
 "text":[
  "Morate popuniti polje tekst."
 ]
} 

I have tried with this but I failed:

 if (response_str != null) {
    try {
        JSONObject jsonObj = new JSONObject(response_str);
        JSONArray arrayJson = jsonObj.getJSONArray("text");

        for (int i = 0; i < arrayJson.length(); i++) {
            JSONObject obj = arrayJson.optJSONObject(i);
            error = obj.getString("text");
        }
    }

Answer

Dan Harms picture Dan Harms · Apr 30, 2014

Your JSONArray is an array of Strings. You can iterate this way

JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");

for (int i = 0; i < arrayJson.length(); i++) {
    String error = arrayJson.getString(i);
    // Do something with each error here
}