abnormal

fun <T> json2List(gson: Gson, json: String? , clazz: Class<T>): List<T>? { val typeToken: TypeToken<List<T>> = object : TypeToken<List<T>>() {} return try { gson.fromJson(json, typeToken.type) } catch (e: Exception) { null } }Copy the code

When using the above function parses com. Google. Gson. Internal. LikedTreeMap connot be case to class, appear this kind of circumstance is usually a problem with generics, because of the type erasure, before parsing can’t get the real type T at runtime.

Processing method

  • Methods a

    fun <T> toList2(json: String? , cls:Class<T>?: List<T> {
        val mList: MutableList<T> = ArrayList()
        try {
            val array = JsonParser().parse(json).asJsonArray
            for (elem in array) {
                mList.add(gson.fromJson(elem, cls))
            }
        } catch (e: Exception) {
        }
        return mList
    }
    Copy the code

    Example:

    val jsonList = "[{\"isSuccess\":false,\"name\":\"a\"},{\"isSuccess\":true,\"name\":\"b\"}]"
    val list4 = GsonKtx.toList2(jsonList,TestBean::class.java)
    println(list4)
    list4.forEach {
      println(it.name)
    }
    Copy the code
  • Method 2

    fun <T> toList(gson: Gson, json: String? , clz:Class<Array<T> >?: List<T>? {
        return try {
            val ts: Array<T> = gson.fromJson(json, clz)
            mutableListOf(*ts)
        } catch (e: Exception) {
            null}}Copy the code

    Example:

    val jsonList = "[{\"isSuccess\":false,\"name\":\"a\"},{\"isSuccess\":true,\"name\":\"b\"}]"
    val list = GsonKtx.toList(Gson(),jsonList,Array<TestBean>::class.java)
    list.forEach {
         println(it.name)
    }
    Copy the code

    reference

Generic methods Gson parsing com. Google. Gson. Internal. LinkedTreeMap always be cast to XXX

Gson generic resolution solution

With gson, LinkedTreeMap cannot be cast to XXX

com.google.gson.internal.LinkedTreeMap