【问题标题】:JSONArray into Kotling Array/List and Setting value in spinnerJSONArray 到 Kotling Array/List 和 Spinner 中的设置值
【发布时间】:2021-03-31 06:32:14
【问题描述】:

我正在执行来自 API 的 HTTP 请求,该请求为我提供了 JSON 数组,我已经能够解析它,但我无法将其转换为列表或数组以便在微调器中设置它。这是我尝试过的:

HTTP 调用:

private fun initiate() {
        var product = 1
        val httpAsync = "https://link_here"
            .httpGet()
            .responseString { request, response, result ->
                when (result) {
                    is Result.Failure -> {
                        val ex = result.getException()
                        println(ex)
                    }
                    is Result.Success -> {
                        val data = result.get()
                        val json = JSONArray(data)

                        println(json)
                        nebulae = listOf(json)
                    }
                }
            }

        httpAsync.join()
    }

响应如下所示:

[{"_nebulae_id":"2","_ss_id":"1","_product_id":"2","product_type":"Dust"},{"_nebulae_id":"2","_ss_id":"3","_product_id":"1","product_type":"Star"}]

这里是微调器代码:

val spinnerProducts: Spinner = findViewById(R.id.spinnerProducts)
        var adapter= ArrayAdapter(this,android.R.layout.simple_list_item_1,nebulae)
        ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            nebulae // insert list
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            spinnerProducts.adapter = adapter
        }

P.S 我是 Kotlin 的新手,已经很久没有使用 Java 了。

【问题讨论】:

  • 你的例子中的星云是什么?是列表还是对象?
  • private lateinit var nebulae: List 它是一个列表
  • 将您的 json 数组转换为 Pojo 对象并将该列表传递给微调器。

标签: android json kotlin


【解决方案1】:

首先nebulae = listOf(json)不会解析json里面的list,只会把整个json作为list的一个元素。

创建用于保存响应的数据类:

data class Nebulae(
    @SerializedName("_nebulae_id") val nebulae_id: String,
    @SerializedName("_ss_id") val ss_id: String,
    @SerializedName("_product_id") val product_id: String
    @SerializedName("product_type") val product_type: String
)

如果你想使用Gson,那么将你的回复转换成这样:

val type = object : TypeToken<List<Nebulae>>() {}.type
val decodedResponse = Gson().fromJson<List<Nebulae>>(json, type)

如果您想使用kotlinx.serialization,则将您的回复转换如下:

 val decodedResponse = Json.decodeFromString<List<Nebulae>>(your_json_string)

【讨论】:

  • 现在可以工作了,只需要格式化它,因为它在微调器中看起来有点奇怪,选项显示如下: Nebulae(nebulae_id=1,ss_id=1,product_id=2,product_type=dust )
  • @Enoch 如果您只想显示“product_type”,则覆盖 Nebulae 类中的 toString() 方法并返回 product_type。
  • @Kunu 谢谢,现在一切都完成了 :) 投票支持你所有的 cmets,他们很有帮助
猜你喜欢
  • 2013-03-05
  • 1970-01-01
  • 2017-09-11
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
相关资源
最近更新 更多