Gson使用嵌套泛型解析对象

问题描述

在我的应用中,我使用BaseResponse类,该类是所有其他网络响应类的父类

open class BaseResponse(

        var status: String = "success",var errors: ArrayList<String>? = null
)

例如,我在我的应用程序中有模型User,并且包含Users类对象的响应看起来是这种方式

class User(val id: Int,val name: String)

class ResponseUser(
        @Serializedname("data")
        val data: User
) : BaseResponse()

这是我用来将json字符串解析为ResponseUser对象的示例代码

fun parsingToRespUser()
{
    val str_reponse = """{"status": "success","errors":null,"data": {"id": 1,"name": "Philipp"}}""""
    val user: ResponseUser = Gson().fromJson(str_reponse,ResponseUser::class.java)
}

所以我的问题是:是否可以用通用的数据字段创建通用的BaseResponse类,并将其以正确的方式进行解析?像这样

class BaseResponseWithData<T>(
        @Serializedname("data")
        val data: T
):BaseResponse()

fun parsingToRespUser()
{
    val str_reponse = """{"status": "success","name": "Philipp"}}""""
    val user: BaseResponseWithData<ModelUser> = Gson().fromJson(str_reponse,BaseResponseWithData::class.java)
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)