Volley之返回数据封装

本文是对volley返回数据进行封装,有3种封装,返回格式分别是:JSON、bean类、List< bean >

下文解析数据使用的是fastjson包,

对于volley请求封装请看:
http://blog.csdn.net/qq_24827089/article/details/54729850

对CallBack进行改写成接口ICallBack:

public interface ICallBack {

    void parseData(String data);

    void onSuccess(T t);

    void onFail(int code, String errMSg);

    void onCancel();

    boolean canCancel();
}

JSON封装:

public class JSONCallBack implements ICallBack {

    @Override
    public void parseData(String data) {
        try {
            JSONObject object = JSON.parseObject(data);
            int code = object.getIntValue("code");
            if (code == 0) {
                onSuccess(object);
            } else {
                onFail(code,object.getString("errmsg"));
            }
        } catch (JSONException e) {
            onFail(-1,"读取服务器数据失败");
        }
    }

    @Override
    public void onSuccess(JSONObject object) {

    }

    @Override
    public void onFail( int code, String errMSg) {

    }

    @Override
    public void onCancel() {

    }

    @Override
    public boolean canCancel() {
        return true;
    }
}

bean类封装:
解析bean的基类,每个请求数据都会返回的code,根据code进行一些处理,如登录失效、参数错误等:

基类:

public class CallBackBean {
    private int code;

    private String errMsg = "";

    public int getCode() {
        return code;
    }

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

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }
}

实现ICallBack:

public class BeanCallBack<T extends CallBackBean> implements ICallBack<T>{

    @Override
    public void parseData(String data) {
        try{
            Class entityClass = null;
            Type t = getClass().getGenericSuperclass();
            if(t instanceof ParameterizedType){
                Type[] p = ((ParameterizedType)t).getActualTypeArguments();
                entityClass = (Class)p[0];
            }
            T bean = JSON.parseObject(data,entityClass);
            if (bean.getCode() == 0) {
                onSuccess(bean);
            } else {
                onFail(bean.getCode(),bean.getErrMsg());
            }
        } catch (Exception e){
            onFail(-1,"读取服务器数据失败");
        }
    }

    @Override
    public void onSuccess(T t) {

    }

    @Override
    public void onFail(int code, String errMSg) {

    }

    @Override
    public void onCancel() {

    }

    @Override
    public boolean canCancel() {
        return true;
    }
}

List< bean >类封装:

服务器返回数据如{“code”:”1”,”list”:[],”a”:”1234”},我们只要list的列表而已,下面实现直接返回list

创建注解,标注列表的key:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ListName {
    String value();
}

实现类:

public class ListCallBack<T extends Object> implements ICallBack<List<T>>{
    @Override
    public void parseData(String data) {
        try{
            JSONObject object = JSON.parseObject(data);
            int code = object.getIntValue("code");
            if (code == 0) {
                Class entityClass = null;
                Type t = getClass().getGenericSuperclass();
                if(t instanceof ParameterizedType){
                    Type[] p = ((ParameterizedType)t).getActualTypeArguments();
                    entityClass = (Class)p[0];
                }

                String listKey = entityClass.getSimpleName();
                ListName annotation = entityClass.getAnnotation(ListName.class);
                if (annotation!=null)
                    listKey = annotation.value();
                onSuccess(JSON.parseArray(object.getString(listKey),entityClass));
            } else {
                onFail(code,object.getString("errMsg"));
            }
        } catch (Exception e){
            onFail(-1,"读取服务器数据失败");
        }
    }

    @Override
    public void onSuccess(List ts) {

    }

    @Override
    public void onFail(int code, String errMSg) {

    }

    @Override
    public void onCancel() {

    }

    @Override
    public boolean canCancel() {
        return true;
    }
}

volley的单例请求只需要改数据解析部分:

 private void makeRequest(int method, String url, final Map map,
                             final ICallBack callBack, final Object tag, final Context context, final boolean showLoad){
        final StringRequest request = new StringRequest(method, url, new Response.Listener() {
            @Override
            public void onResponse(String response) {
            //改了这里
                if (callBack!=null)
                    callBack.parseData(response);
                dismissIfNeed();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (callBack!=null) {
                    callBack.onFail(-2, "请求服务器失败");
                }
                dismissIfNeed();
            }
        }) {
            @Override
            protected Map getParams() throws AuthFailureError {
                if (map != null)
                    return map;
                return super.getParams();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        if (tag!=null) {
            request.setTag(tag);
        }
        requestQueue.add(request);
        dialog = null;
        if (showLoad && context!=null && tag!=null) {
            dialog = new ProgressDialog(context);
            dialog.setCancelable(false);
            dialog.show();
            this.tag = tag;
            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK
                            && event.getAction() == MotionEvent.ACTION_UP) {
                        if (callBack != null && callBack.canCancel()) {
                            callBack.onCancel();
                            cancelRequest(tag);
                            dismissIfNeed();
                        }
                    }
                    return false;
                }
            });
        }
    }

到这里封装结束,使用方法:

 new HttpUtils.RequestBuilder().bindUrl("")
                .bindMap(map)
                .bindShow(true)
                .bindContext(this)
                .bindTag("TAST")
                //new ListCallBack
                .bindCallBack(new BeanCallBack(){

                    @Override
                    public void onSuccess(DataBean dataBean) {
                        Log.e("BeanCallBack", JSON.toJSONString(dataBean));
                    }
                }).build();

其中Bean类:

   @ListName("list")
    public class Bean{
        private String a;
        private String b;

        public String getA() {
            return a;
        }

        public void setA(String a) {
            this.a = a;
        }

        public String getB() {
            return b;
        }

        public void setB(String b) {
            this.b = b;
        }
    }

结束。

你可能感兴趣的:(Android)