gpt4 book ai didi

android - 将 JSONArray 转换为通用类型列表的函数

转载 作者:行者123 更新时间:2023-11-29 00:53:23 28 4
gpt4 key购买 nike

我的 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>

最佳答案

您可以像这样使用 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)!!
}

关于android - 将 JSONArray 转换为通用类型列表的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57355082/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com