使用Retrofit2+RxAndroid+Okhttp3 获取服务器数据时,格式不统一处理

通常开发情况下,后台一般会给出约定好的格式:

{
    "code": 200,
    "msg": "成功",
    "data": {}
}

但是,有些后台开发者,根本不管前台开发方便与否,自成一体的风格,不按约定成俗的格式规范,返回的格式不统一,data 可能是空数组,空JSON  , 字符串等,如果不做处理,会出现JSON 解析时异常(com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 4 column 14 path $.data),所以我们只能自定义转换器,对JSON 数据进行处理.

1. 定义一个 ApiResponse 基类

public class ApiResponse<T> {

    private int code;
    private String msg;
    private T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

}

2. 自定义响应体转换器 CustomResponseConverter 继承 Converter

public class CustomResponseConverter<T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private TypeAdapter<T> adapter;
    private Type mType;


    CustomResponseConverter(Gson gson, TypeAdapter<T> mAdapter, Type mType) {
        this.gson = gson;
        this.adapter = mAdapter;
        this.mType = mType;

    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        ApiResponse response = new ApiResponse();
        try {
            String body = value.string();

            JSONObject json = new JSONObject(body);

            int ret = json.optInt("code");
            String msg = json.optString("msg", "");

            if (ret == 200) {
                return gson.fromJson(body, mType);
            } else {
                response.setCode(ret);
                response.setMsg(msg);
                response.setData(json.opt("data"));
                return (T) response;
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            value.close();
        }
    }
}

3. 自定义转换工厂类 CustomGsonConverterFactory 继承  Converter.Factory

public final class CustomGsonConverterFactory extends Converter.Factory {

    public static CustomGsonConverterFactory create() {
        return create(new Gson());
    }

    public static CustomGsonConverterFactory create(Gson gson) {
        return new CustomGsonConverterFactory(gson);
    }

    private final Gson gson;

    private CustomGsonConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new CustomResponseConverter<>(gson, adapter, type);
    }

    @Nullable
    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations, Retrofit retrofit) {
        return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
    }

4.  在构造Retrofit 对象时添加 自定义转换器

 ApiServer mAPIService = new Retrofit.Builder()
      .client(mOkHttpClient)
      .baseUrl("https://raw.githubusercontent.com/")
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
      // 添加自定义转换器
      .addConverterFactory(CustomGsonConverterFactory.create())
      .build()
      .create(ApiServer.class);

 5. 现在就可以定义成功返回时的实体类 接口。

public interface ApiServer {

    @GET("getUserInfo")
    Observable<ApiResponse<ImageInfo>> getInfo();


}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值