基于Retrofit Kotlin解决Gson TypeToken<T> T不确定的解决办法

解决办法

1自定义类实现ParameterizedType接口,用来获取用户传入的类型(T用来解决泛型转换问题,跟业务无关)

class ParameterizedTypeImpl<T>(private val raw: Class<T>, private val args: Array<Type>) :ParameterizedType {

    override fun getRawType(): Type {
        return this.raw
    }

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

    override fun getActualTypeArguments(): Array<Type> {
        return this.args
    }
}

2 在框架中使用

abstract class DefaultObserver<M:Any>:Observer<String>{

    private val baseUI:BaseUI

    constructor(baseUI: BaseUI){
        this.baseUI = baseUI
    }
    constructor(baseUI: BaseUI,showProgress:Boolean){
        this.baseUI = baseUI
        if(showProgress)
            this.baseUI.showProgress("请稍后")
    }

    override fun onSubscribe(d: Disposable) {
        this.baseUI.addRxDestroy(d)
    }

    override fun onComplete() {
        this.baseUI.dismissProgress()
    }

    override fun onNext(t: String) {
        if(t == ""){
            onError(ExceptionReason.PARAMS_ERROR)
            this.baseUI.shortMsg("服务器异常")
        }else{
            try {
                val obj = JSONObject(t)
                when(obj.getInt("status")){
                    1 -> {
                        val mClass:Class<M> =
                            (((javaClass.genericSuperclass) as ParameterizedType))
                                .actualTypeArguments[0] as Class<M>
                        val type:Type = ParameterizedTypeImpl<M>(mClass, arrayOf(mClass))
                        val data:M = Gson().fromJson(t,type)
                        onSuccess(data)
                    }
                    100 -> this.baseUI.shortMsg("用户认证失败")
                    else ->{
                        this.baseUI.shortMsg(obj.getString("info"))
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                onError(ExceptionReason.PARSER_ERROR)
                this.baseUI.shortMsg("数据解析失败")
            }
        }
    }

    override fun onError(e: Throwable) {
        //this.baseUI.dismissProgress()
        e.printStackTrace()
        if(e is HttpException){
            this.baseUI.shortMsg("网络异常")
            onError(ExceptionReason.BAD_NETWORK)
        }else if(e is ConnectException || e is UnknownHostException || e is NoRouteToHostException){
            this.baseUI.shortMsg("远程服务异常")
            onError(ExceptionReason.CONNECT_ERROR)
        }else if(e is InterruptedException || e is SocketTimeoutException){
            this.baseUI.shortMsg("连接超时")
            onError(ExceptionReason.CONNECT_TIMEOUT)
        }else if(e is JsonParseException || e is JSONException || e is ParseException){
            this.baseUI.shortMsg("数据解析失败")
            onError(ExceptionReason.PARSER_ERROR)
        }else{
            this.baseUI.shortMsg("未知错误")
            onError(ExceptionReason.UNKNOWN_ERROR)
        }
    }

    abstract fun onError(error:ExceptionReason)

    abstract fun onSuccess(data:M)

    /**
     * exception enum class
     */
    enum class ExceptionReason{
        PARSER_ERROR,
        BAD_NETWORK,
        CONNECT_ERROR,
        CONNECT_TIMEOUT,
        UNKNOWN_ERROR,
        PARAMS_ERROR
    }
}

3 主要步骤

val mClass:Class<M> =
                            (((javaClass.genericSuperclass) as ParameterizedType))
                                .actualTypeArguments[0] as Class<M>
                        val type:Type = ParameterizedTypeImpl<M>(mClass, arrayOf(mClass))
                        val data:M = Gson().fromJson(t,type)

结语

小弟第一次来CSDN,未来会和大家共同成长

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值