【问题标题】:Generics problems encountered by Kotlin and GSONKotlin 和 GSON 遇到的泛型问题
【发布时间】:2018-09-13 17:58:32
【问题描述】:

我尝试写一个网络请求函数,它的作用是分析通用格式并提供数据内容给回调。

这是我定义的类:

data class Response<T>(
    val code: Int = 0,
    @JvmSuppressWildcards
    var data: ArrayList<T>,
    val message: String = "")

在这个类中'code'和'message'是固定的,'data'有不同的类型

选择一项数据:

data class TestData(
    @SerializedName("create_by")
    val createBy: String = "",
    @SerializedName("create_time")
    val createTime: String = "",
    @SerializedName("name")
    val name: String = "",
    @SerializedName("id")
    val id: String = "")

还有我的网络请求功能:

fun <T> post(callBack: (ArrayList<T>) -> Unit) {
    ...
     override fun onSuccess(response:Response<String>) {
          val result = gson.fromJson<Response<T>>(response.body().reader(),Response::class.java)
          when{
              result.code==200-> callBack.invoke(result.data)
          }
     }
    ...
}

在活动中使用它:

Request.addr(Constants.GET_TEST)
       .post<TestData> {
            tv.text = it[0].name
        }

当我使用 Gson 解析服务器返回的数据,并想使用 JavaBean 时,Logcat 抛出这个异常:

java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap 无法转换为 com.example.network.response.TestData

我尝试使用TypeToken来解决这个问题,但还是不行。

【问题讨论】:

    标签: android kotlin gson


    【解决方案1】:

    这是因为解析器在运行时无法获取真正的类型 T。 这个扩展对我有用

    内联 fun Gson.fromJson(json: String) = this.fromJson(json, object: TypeToken() {}.type)!!

    然后您需要按照 IDE 推荐的方法进行修改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多