android how to convert json array to string array

Viewed 48834

I have an app where I fetch data from server(json) in the form of array & by using the index i used in my app, like below.

JSONObject topobj = new JSONObject(page);
JSONObject innerobj = topobj.getJSONObject("restarutant");
JSONArray phone = innerobj.getJSONArray("phone");
textViewPhone.setText("Phone: " + phone.get(0).toString() + " ,"
                    + phone.get(1).toString());

for small size array I can get like this. But when array contains 'n' no of elements and dynamically i have to use this, at that time it required to convert into String Array. Can anybody tell me how I convert the json array to String array ? Thank you

6 Answers

Another elegant kotlin way:

val list = jsonArray.map { jsonElement -> jsonElement.toString() }

And just convert to array if needed

If you are using org.json package, Here is the kotlin way of converting json array to string array.

// get json array
val jsonArray = json.getJSONArray("field")
// convert to string array
val stringArray = Array(jsonArray.length()) { jsonArray.getString(it) }
Related