okgo二次封装

okgo二次封装


优点:省略重复的解析步骤

okgo依赖:implementation ‘com.lzy.net:okgo:3.0.4’
fastjson依赖: implementation ‘com.alibaba:fastjson:1.2.55’

封装

 package com.example.app_okgo;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.callback.AbsCallback;

import okhttp3.Response;

public abstract class Mygogog<T> extends AbsCallback<T> {
    private Class<T> aClass;   // 传Entity

    public Mygogog(Class<T> aClass) {
        this.aClass = aClass;
    }

    @Override
    public T convertResponse(Response response) throws Throwable {
        if (response.body()==null){
            return null;
        }
        if (aClass == null){
            return null;
        }
        String string = response.body().string();
        T t = JSON.parseObject(string, aClass);
        return t;
    }
}

使用

// XiaEntity 资源对象
OkGo.<XiaEntity>get(url).execute(new Mygogog<XiaEntity>(XiaEntity.class) {
    @Override
    public void onSuccess(Response<XiaEntity> response) {
        Toast.makeText(MainActivity.this, "" + response.body().getData().get(0).getTitle(), Toast.LENGTH_SHORT).show();
    }
});

你可能感兴趣的:(Android2)