Convert JSONArray to String Array
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"));
}
Simplest and correct code is:
public static String[] toStringArray(JSONArray array) {
if(array==null)
return null;
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.
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;
}
shameless hack:
String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");
You can loop to create the String
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
String[] stringArray = list.toArray(new String[list.size()]);