user2369
user2369

Reputation: 147

Can't convert JSONArray into a list (Kotlin)

This is my string:

{"array":[{"message":"test1","name":"test2","creation":"test3"},{"message":"test1","name":"test2","creation":"test3"}]}

And I want it get that array into a list of object in Kotlin app for Android. I tried to do it using two examples from this site... So here is my code (res = that string):

val gson = Gson()
val obj = gson.fromJson(res, JsonObject::class.java)
val arr = obj.getAsJsonArray("array")

println(arr.toString())
val list1 : List<JThread> = gson.fromJson(arr, object : TypeToken<List<JThread>>() {}.type)
val list2 = gson.fromJson(arr, Array<JThread>::class.java).asList()

for (x in list1){
   println(x.message)
}
for (x in list2){
   println(x.message)
}   

However I'm only getting null in x.message. I don't know what can go wrong. I also tried changing arr to arr.toString() everywhere and that didn't work either.

Also JThread is:

object JThread {
var message: String? = null
var name: String? = null
var creation: String? = null }     

Upvotes: 5

Views: 11620

Answers (2)

Michael Avoyan
Michael Avoyan

Reputation: 211

This can be done without GSON or any other third party library:

@Throws(JSONException::class)
fun JSONObject.toMap(): Map<String, Any> {
    val map = mutableMapOf<String, Any>()
    val keysItr: Iterator<String> = this.keys()
    while (keysItr.hasNext()) {
        val key = keysItr.next()
        var value: Any = this.get(key)
        when (value) {
            is JSONArray -> value = value.toList()
            is JSONObject -> value = value.toMap()
        }
        map[key] = value
    }
    return map
}

@Throws(JSONException::class)
fun JSONArray.toList(): List<Any> {
    val list = mutableListOf<Any>()
    for (i in 0 until this.length()) {
        var value: Any = this[i]
        when (value) {
            is JSONArray -> value = value.toList()
            is JSONObject -> value = value.toMap()
        }
        list.add(value)
    }
    return list
}

Usage to convert JSONArray to List:

val jsonArray = JSONArray(jsonArrStr)
val list = jsonArray.toList()

Usage to convert JSONObject to Map:

val jsonObject = JSONObject(jsonObjStr)
val map = jsonObject.toMap()

More info is here

Upvotes: 6

samaromku
samaromku

Reputation: 559

Use this code:

import com.google.gson.annotations.SerializedName
import com.google.gson.Gson

data class Array(
    @SerializedName("message")
    var message: String,
    @SerializedName("name")
    var name: String,
    @SerializedName("creation")
    var creation: String
)

data class Example(
    @SerializedName("array")
    var array: List<Array>? = null
)

private fun fromJson(json:String):Example{
    return Gson().fromJson<Example>(json, Example::class.java)
}

PS: I made it with this site:http://www.jsonschema2pojo.org/

Upvotes: 0

Related Questions