【问题标题】:A function to convert JSONArray to list of generic type将 JSONArray 转换为泛型列表的函数
【发布时间】: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&lt;News&gt;(),它总是返回错误com.google.gson.internal.LinkedTreeMap cannot be cast to com.example.News

知道我哪里出错了,以及如何解决吗?

编辑: 我项目中的每个响应总是作为加密字符串接收,这就是为什么我必须自己映射响应并且不能将响应类型放入 Call 方法中。这是我的Call 函数看起来像

@POST("endpoint")
fun service(@Body body: RequestBody): Call<String>

【问题讨论】:

  • 知道我哪里出错了你为什么要泛化这个
  • @TimCastelijns 实际上,除了NewsProduct 之外,它还有更多对象。这就是为什么我想结合这个函数来缩短我的代码。
  • 你用什么来发送请求和接收响应?
  • @faranjit OkHttp 使用 Retrofit2 作为 REST 客户端。但我确定网络进程没有问题。

标签: android json kotlin


【解决方案1】:

你可以像这样使用TypeToken.getParameterized

inline fun <reified T> JSONObject.toList(): List<T> {
    val typeToken = TypeToken.getParameterized(List::class.java, T::class.java)
    return Gson().fromJson<List<T>>(json, typeToken.type)!!
}

【讨论】:

  • 不错的解决方案,这就是我要找的。​​span>
【解决方案2】:

你的response 类应该如下所示

class ResponseList<E> {
  var message:String
  var data:ArrayList<E>
}

你可以打电话给你的API 喜欢

@GET("url")
fun getNews():Call<ResponseList<News>>

【讨论】:

  • 感谢您的建议,但我项目中的每个请求和响应始终以加密字符串的形式发送。这就是为什么我不能将响应类型放在Call 方法中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2010-12-02
相关资源
最近更新 更多