基于Retrofit Kotlin解决Gson TypeToken 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,未来会和大家共同成长