Enoch
Enoch

Reputation: 1001

JSONArray into Kotling Array/List and Setting value in spinner

I am performing a HTTP request from an API that gives me a JSON Array, I have been able to parse it but I am not able to convert it into a list or array in order to set it within the spinner. Here is what I have tried:

HTTP CALL:

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()
    }

the response looks like this:

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

Here is the spinner code:

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 I am new to Kotlin and it's been very long time since I used Java.

Upvotes: 0

Views: 132

Answers (1)

Y.Kakdas
Y.Kakdas

Reputation: 843

Firstly, nebulae = listOf(json) will not parse the list inside the json, will only put the whole json as an element of a list.

Create your data class for holding response:

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
)

If you want to use Gson, then convert your response like that:

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

If you want to use kotlinx.serialization, then convert your response as follows:

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

Upvotes: 1

Related Questions