【问题标题】:Android Kotlin - convert jsonArray to Array<String>Android Kotlin - 将 jsonArray 转换为 Array<String>
【发布时间】:2019-05-12 23:06:21
【问题描述】:

我从 API 得到一个数组:

val pics = response.getJSONArray("pics")

pics 包含类似:

["https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/19\/55\/497173801955.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/10\/34\/242830811034.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/86\/23\/808728238623.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/90\/41\/146747399041.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/47\/41\/672475854741.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/63\/94\/771076926394.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/36\/42\/182330463642.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/29\/96\/948397532996.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/82\/54\/761385508254.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/41\/42\/142837364142.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/66\/25\/215324906625.jpg"]

我需要把它放到ArrayList&lt;String&gt;

这是将 JAVA 解决方案转换为 kotlin 后的多次尝试之一:

val list = ArrayList<String>()
for (i in 0 until pics.length()) {
   list.add(pics.getJSONObject(i).getString("name"))
}

然后当我尝试在 ViewPager 中使用 list 时,我得到类型不匹配:

Required: Array<String>

Found:kotlin.collections.ArrayList<String

如何做到这一点??

为什么不能像 PHP smh 那样只是简单的数组(),这太烦人了

【问题讨论】:

    标签: android json kotlin


    【解决方案1】:

    Array&lt;String&gt; 和 ArrayList&lt;String&gt; 是两种不同的类型。

    您需要提供的是Array&lt;String&gt;,但您实际提供的是ArrayList&lt;String&gt;。

    val list = Array(pics.length()) {
        pics.getString(it)
    }
    

    【讨论】:

    • 如果您有一个实际的 JSONArray 并且想要转换为一个 Array,那么答案将无济于事
    • @Justin 你能详细说明一下吗,JSONArray 从List 实现length() 并有getString(int) 方法来检索第n 个位置的String 元素,这对你不起作用吗?跨度>
    • 感谢您的回复。我现在实际上已经开始工作了。我只是在评论它对我不起作用的事实,使用 json 库。我最终使用了迭代器并循环并复制到一个数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多