Kotlin Gson解析泛型对象

API:API说明文档:www.juhe.cn/docs/api/id…
接口地址:v.juhe.cn/wepiao/quer…
API返回的json:

{"reason":"请求成功","result":{"h5url":"http:\/\/v.juhe.cn\/wepiao\/go?key=xxxxxxxxx","h5weixin":"http:\/\/v.juhe.cn\/wepiao\/go?key=xxxxxxxxxx&s=weixin"},"error_code":0}复制代码
{
    "reason": "请求成功",
    "result": {
        "h5url": "http://v.juhe.cn/wepiao/go?key=xxxxxxxxxxxxx",
        "h5weixin": "http://v.juhe.cn/wepiao/go?key=xxxxxxxxxx&s=weixin"
    },
    "error_code": 0
}复制代码

实体类

  • H5TicketUrl
    data class H5TicketUrl(val h5url: String, val h5weixin: String)复制代码
  • H5TicketResult
    data class H5TicketResult(val error_code: Int, val reason: String, val result: H5TicketUrl)复制代码
  • ProjectBaseResult
    data class ProjectBaseResult(val reason: String, val error_code: Int, val result: M)复制代码

    请求

    val url = freeApi.reqUrl + "?key=" + APP_KEY // 请求url
    val resultJson = URL(url).readText()  // 发送请求,resultJson为返回的json复制代码

    解析Json-method 1

    val result = Gson().fromJson(resultJson, H5TicketResult::class.java)复制代码

    解析Json-method 2

    val type = object : TypeToken>() {}.type
    val result = Gson().fromJson>(resultJson, type)复制代码

    解析Json-method 3

    val result = object : BaseResult() {}.fromJson(resultJson)复制代码
abstract class BaseResult : ParameterizedType {

    override fun getRawType(): Type {
        return ProjectBaseResult::class.java
    }

    override fun getOwnerType(): Type? {
        return null
    }

    override fun getActualTypeArguments(): Array {
        val superclass = this.javaClass.genericSuperclass
        if (superclass is Class<*>) {
            throw RuntimeException("Missing type parameter.")
        }
        return (superclass as ParameterizedType).actualTypeArguments
    }

    fun fromJson(json: String): ProjectBaseResult {
        return Gson().fromJson>(json, this)
    }

}复制代码

转载于:https://juejin.im/post/59c47659f265da066908656e

你可能感兴趣的:(Kotlin Gson解析泛型对象)