Convert JSONArray to String Array
Simplest and correct code is:
public static String[] toStringArray(JSONArray array) {
if(array==null)
return new String[0];
String[] arr=new String[array.length()];
for(int i=0; i<arr.length; i++) {
arr[i]=array.optString(i);
}
return arr;
}
Using List<String>
is not a good idea, as you know the length of the array.
Observe that it uses arr.length
in for
condition to avoid calling a method, i.e. array.length()
, on each loop.
Take a look at this tutorial. Also you can parse above json like :
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}
public static String[] getStringArray(JSONArray jsonArray) {
String[] stringArray = null;
if (jsonArray != null) {
int length = jsonArray.length();
stringArray = new String[length];
for (int i = 0; i < length; i++) {
stringArray[i] = jsonArray.optString(i);
}
}
return stringArray;
}