【发布时间】:2019-08-05 08:49:37
【问题描述】:
我的 JSON 数据表单响应如下所示
{
"message": "",
"data" : [...]
}
data 包含一个数组
data class News(
@SerializedName("id") val id: Int,
@SerializedName("title") val title: String,
@SerializedName("description") val desc: String
)
或
data class Product(
@SerializedName("id") val id: Int,
@SerializedName("name") val name: String
)
基于我击中的端点。
为了从 json 对象中获取数据,我创建了 2 个函数
fun JSONObject.toNewsList() = Gson().fromJson<List<News>>(getJSONArray("data").toString(),
object : TypeToken<List<News>>(){}.type)!!
fun JSONObject.toProductList() = Gson().fromJson<List<Product>>(getJSONArray("data").toString(),
object : TypeToken<List<Product>>(){}.type)!!
这些函数完美运行,直到我尝试使用泛型类型将它们组合成一个函数,因为参数看起来像这样
fun <T> JSONObject.toList() = Gson().fromJson<List<T>>(getJSONArray("data").toString(),
object : TypeToken<List<T>>(){}.type)!!
每当我调用函数jsonResponse.toList<News>(),它总是返回错误com.google.gson.internal.LinkedTreeMap cannot be cast to com.example.News
知道我哪里出错了,以及如何解决吗?
编辑:
我项目中的每个响应总是作为加密字符串接收,这就是为什么我必须自己映射响应并且不能将响应类型放入 Call 方法中。这是我的Call 函数看起来像
@POST("endpoint")
fun service(@Body body: RequestBody): Call<String>
【问题讨论】:
-
知道我哪里出错了你为什么要泛化这个
-
@TimCastelijns 实际上,除了
News和Product之外,它还有更多对象。这就是为什么我想结合这个函数来缩短我的代码。 -
你用什么来发送请求和接收响应?
-
@faranjit OkHttp 使用 Retrofit2 作为 REST 客户端。但我确定网络进程没有问题。