Kotlin如何将JSONArray映射到Type(流) [英] Kotlin how to Map JSONArray to Type (Stream)
本文介绍了Kotlin如何将JSONArray映射到Type(流)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将我的JSONArray
映射到Array<String?>
.
I'm trying to map my JSONArray
to a Array<String?>
.
我正在这样做:
fun getTextResponse(responseJson: JSONObject): Array<String?>{
val resultData = responseJson.getJSONArray("data")
.getJSONObject(0)
.getJSONArray("result")
return resultData.map{ it.getString("label") }.toTypedArray()
}
但是it
的类型不是JSONObject
,有什么办法可以强制将其键入JSONObject
吗?
But it
is not typed as a JSONObject
, is there any way I can force type it to JSONObject
?
推荐答案
问题是resultData
具有类型JSONArray
,这是不覆盖Kotlin/Java Array
接口的JSON实用程序类因此没有map
函数.
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) }
}
这篇关于Kotlin如何将JSONArray映射到Type(流)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文