美文网首页
2019-11-19 Gson解析泛型T

2019-11-19 Gson解析泛型T

作者: 兣甅 | 来源:发表于2019-11-19 19:59 被阅读0次

    具体使用见https://github.com/caiyoufei/ABase

    1.ParameterizedType

    import cc.ab.base.net.http.response.BaseResponse;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import java.util.List;
    import org.jetbrains.annotations.NotNull;
    public class BaseParameterizedTypeImpl implements ParameterizedType {
      private final Class raw;
      private final Type[] args;
    
      private BaseParameterizedTypeImpl(Class raw, Type[] args) {
        this.raw = raw;
        this.args = args != null ? args : new Type[0];
      }
    
      public static Type typeOne(Class<?> clazz) {
        return new BaseParameterizedTypeImpl(BaseResponse.class, new Class[] { clazz });
      }
    
      public static Type typeList(Class<?> clazz) {
        // 生成List<T> 中的 List<T>
        Type listType = new BaseParameterizedTypeImpl(List.class, new Class[] { clazz });
        // 根据List<T>生成完整的Response<List<T>>
        return new BaseParameterizedTypeImpl(BaseResponse.class, new Type[] { listType });
      }
    
      @NotNull @Override
      public Type[] getActualTypeArguments() {
        return args;
      }
    
      @NotNull @Override
      public Type getRawType() {
        return raw;
      }
    
      @Override
      public Type getOwnerType() {
        return null;
      }
    }
    

    2.BaseResponse

    data class BaseResponse<out T>(
      val errorCode: Int = -1,//正常接口使用的状态码
      var errorMsg: String? = null,//code异常对应的信息提示
      val data: T? = null//正常返回的数据信息
    )
    

    3.真正转换

     private inline fun <reified T> flatMapSingle(
        result: Result<String, FuelError>
      ): Single<BaseResponse<T>> {
        return if (result.component2() == null) {
          Single.just(
              converWanData(result.component1(), BaseParameterizedTypeImpl.typeOne(T::class.java))
          )
        } else {
          Single.error(converFuelError(result.component2()))
        }
      }
    
      private inline fun <reified T> flatMapSingleList(
        result: Result<String, FuelError>
      ): Single<BaseResponse<MutableList<T>>> {
        return if (result.component2() == null) {
          Single.just(
              converWanData(result.component1(), BaseParameterizedTypeImpl.typeList(T::class.java))
          )
        } else {
          Single.error(converFuelError(result.component2()))
        }
      }
    
      //数据转换(可能抛出异常)
      @Throws
      private fun <T> converWanData(
        response: String?,
        type: Type
      ): BaseResponse<T> {
        if (response.isNullOrBlank()) throw converDataError()
        try {
          val result: BaseResponse<T> = GsonUtils.fromJson(response, type)
          if (globalErrorCode.contains(result.errorCode)) {
            result.errorMsg = null
            dealGlobalErrorCode(result.errorCode)
          }
          return result
        } catch (e: Exception) {
          e.printStackTrace()
        }
        throw converDataError()
      }
    
      //统一处理
      private fun dealGlobalErrorCode(errorCode: Int) {
        val activity = ActivityUtils.getTopActivity()
        activity?.let { ac ->
          when (errorCode) {
            //未登录
            ErrorCode.NO_LOGIN -> {
              ac.runOnUiThread {
                ac.toast(R.string.need_login)
                LoginActivity.startActivity(ac)
              }
            }
            else -> {
            }
          }
        }
      }
    
    异常处理

    相关文章

      网友评论

          本文标题:2019-11-19 Gson解析泛型T

          本文链接:https://www.haomeiwen.com/subject/bymgictx.html