问题
I'm trying to map my JSONArray
to a Array<String?>
.
I'm doing it like this:
fun getTextResponse(responseJson: JSONObject): Array<String?>{
val resultData = responseJson.getJSONArray("data")
.getJSONObject(0)
.getJSONArray("result")
return resultData.map{ it.getString("label") }.toTypedArray()
}
But it
is not typed as a JSONObject
, is there any way I can force type it to JSONObject
?
回答1:
The problem is that resultData
has a type of JSONArray
, which is a JSON utility class that doesn't overrides Kotlin/Java Array
interface and thus doesn't have a map
function.
You have to retrieve each string by index and generate new array like this:
fun getTextResponse(responseJson: JSONObject): Array<String?> {
val resultData = responseJson.getJSONArray("data")
.getJSONObject(0)
.getJSONArray("result")
return Array<String?>(resultData.length()) { i -> resultData.getString(i) }
}
回答2:
What jackqack proposed in his answer is what you should do, I just want to add that since you want to return an Array<String?>
you should also map exceptions to null. This will make your code more robust. The generic type argument can be inferred too, so it can be omitted.
fun getTextResponse(responseJson: JSONObject): Array<String?> {
val resultData = responseJson.getJSONArray("data")
.getJSONObject(0)
.getJSONArray("result")
return Array(resultData.length()) { i ->
try {
resultData.getString(i)
} catch (e: JSONException){
null
}
}
}
回答3:
The problem is that your resutData
does not have a map
function! See https://developer.android.com/reference/org/json/JSONArray.
What you can do instead is iterate over the JSONArray and add every entry to your new Array, like this:
fun getTextResponse(responseJson: JSONObject): Array<String?>{
val resultData = responseJson.getJSONArray("data")
.getJSONObject(0)
.getJSONArray("result")
val arrayList = ArrayList<String>()
for (i in 0..resultData.length()) {
arrayList.add(resultData[i].toString())
}
return arrayList.toArray(arrayOfNulls<String>(arrayList.size))
}
来源:https://stackoverflow.com/questions/54136316/kotlin-how-to-map-jsonarray-to-type-stream