老师,如果返回的时候是一个泛型,gson似乎就没法转换,要怎么办?
来源:10-3 案例:仿 Retrofit 反射读取注解请求网络

毛豆先生在广州
2021-03-21
老师,如果返回的时候是一个泛型,gson似乎就没法转换,要怎么办?下面这样的
suspend fun <P, T> getTest(param: P): BaseResponse<T> where P : BaseParam, T : BaseResult
如果按照您写的这样,通过method.genericReturnType获取类型
Gson().fromJson(it, method.genericReturnType)
gson会提示
Not enough information to infer type variable T
如果用
Gson().fromJson(it, method.returnType)
这种,运行时又会报
com.google.gson.internal.LinkedTreeMap cannot be cast to BaseResponse
这个时候应该要怎么处理?T我在使用前我自己也不知道啊
写回答
1回答
-
bennyhuo
2021-03-23
挂起函数的返回值类型是 Object,不是 BaseResponse<T>,你要想知道 T 的类型,你得用 suspend 函数生成的 Continuation 参数的泛型参数来获取。
032021-03-23
相似问题