Android数据加载及Json解析——框架版

方法调用

new ApiUser(this).initData(new ApiRequest() {

            @Override
            public void onResult(BeanRequest bean) {
            //如果接口调用不成功,给予提示
                if (!bean.isSuccess()) {
                    UtilToast.show(Activitymain.this, bean.getErrInfo(), UtilToast.STYLE_ERROR);
                }
                //Json数据解析:BeanInitData 数据实体类
                BeanInitData data = (BeanInitData) ApiPublic.readJson((JSONObject) bean.getData(), BeanInitData.class);

            }
        });

接下来是方法过程:
1、创建实体类:

public class BeanInitData {
    private int jobApplicantCount;//":33,"
    private int employJobCount;//":21,"
    private int enterpriseCount;//":14,"
    private ArrayList<BeanAdv> ads;
    public int getJobApplicantCount() {
        return jobApplicantCount;
    }
    public void setJobApplicantCount(int jobApplicantCount) {
        this.jobApplicantCount = jobApplicantCount;
    }
    public int getEmployJobCount() {
        return employJobCount;
    }
    public void setEmployJobCount(int employJobCount) {
        this.employJobCount = employJobCount;
    }
    public int getEnterpriseCount() {
        return enterpriseCount;
    }
    public void setEnterpriseCount(int enterpriseCount) {
        this.enterpriseCount = enterpriseCount;
    }
    public ArrayList<BeanAdv> getAds() {
        return ads;
    }
    public void setAds(ArrayList<BeanAdv> ads) {
        this.ads = ads;
    }

}

2、所有接口调用统一写在一起,

public class ApiUser {

    private Context ctx;

    public ApiUser(Context ctx) {
        this.ctx = ctx;
    }

    public void initData(ApiRequest request) {
    // ApiPublic.SERERIP为接口url
        String url = ApiPublic.SERERIP + "initData.json";
        HttpParam param = new HttpParam();
        ApiPublic.startHttpPost(ctx, url, param, request);
    }
    //登陆
    //参数String account,String password,String loginFrom
    public void login(String account,String password,String loginFrom,ApiRequest request) {
        String url = ApiPublic.SERERIP + "login.html";
        HttpParam param = new HttpParam();
        param.addParams("account", account);
        param.addParams("password", password);
        param.addParams("loginFrom", loginFrom);
        ApiPublic.startHttpPost(ctx, url, param, request);
    }
}

3、ApiPublic包含分页,不分页Json解析

public class ApiPublic {

public final static String SERERIP = "http://write.blog.csdn.net/mdeditor/api/";

/**
 * 开始调用接口:POST方式
 * @param url
 * @param param
 * @param request
 */
public static void startHttpPost(Context ctx, String url, HttpParam param, ApiRequest request) {
    HttpRequest http = new HttpRequest(url, param, 0, request);
    http.execute();
}

public static void startHttpPost(String url, HttpParam param, ApiRequest request) {
    HttpRequest http = new HttpRequest(url, param, 0, request);
    http.execute();
}

/**
 * 开始调用接口:POST方式,传输文件
 * @param url
 * @param param
 * @param request
 */
public static void startHttpPostFile(Context ctx, String url, HttpParam param, ApiRequest request) {
    HttpRequest http = new HttpRequest(url, param, 1, request);
    http.execute();
}

public static void startHttpPostFile(String url, HttpParam param, ApiRequest request) {
    HttpRequest http = new HttpRequest(url, param, 1, request);
    http.execute();
}

/**
 * 取消接口调用
 */
public static void httpTaskCancel() {
    HttpRequest http = new HttpRequest();
    http.onCancelled();
}

/**
 * 通用的JSON解析
 * 
 * @param result 传入JSON字符串
 * @return String 成功返回为"",失败返回错误描述
 */
public static BeanRequest readJsonUtil(String result) {
    if (TextUtils.isEmpty(result)) {
        return new BeanRequest().setError("无响应数据");
    }

    try {
        JSONObject jsonObject = new JSONObject(result);
        if (jsonObject.isNull("status")) {
            return new BeanRequest().setError("受理失败");
        }

        // 0成功、1错误、2异常
        int Status = jsonObject.getInt("status");
        if (Status != 0) {
            String description = jsonObject.getString("desc");
            return new BeanRequest().setError(description);
        }

        BeanRequest bean = new BeanRequest();
        bean.setSuccess(true);
        bean.setResult(result);
        bean.setData(jsonObject.isNull("data") ? null : jsonObject.get("data"));
        return bean;

    } catch (JSONException e) {
        e.printStackTrace();
        return new BeanRequest().setError("数据异常");
    }
}

/**
 * 解析JSON对象,不含分页
 * 
 * @param result json数据
 * @param entityClass 实体类
 * @return
 */
public static <T> Object readJson(final JSONObject result, Class<T> entityClass) {
    if (null == result)
        return null;

    return new Gson().fromJson(result.toString(), entityClass);
}

/**
 * 解析JSON数组,含分页
 * 数据示例:{"total":xx,"rows":[]}
 * @param result json数据
 * @param entityClass 实体类
 * @return
 */
public static <T> List readJsonListPage(final JSONObject result, BeanPage page, Class<T> entityClass) {
    if (null == result)
        return null;

    try {
        int total = result.getInt("total");
        page.setTotal(total);

        JSONArray array = result.getJSONArray("rows");
        List<T> list = new ArrayList<T>();
        Gson gson = new Gson();

        int size = array.length();
        for (int i = 0; i < size; i++) {
            list.add(gson.fromJson(array.getString(i), entityClass));
        }

        return list;
    } catch (JSONException e) {
        return null;
    }
}

/**
 * 解析JSON数组,不含分页
 * 
 * @param result json数据
 * @param entityClass 实体类
 * @return
 */
public static <T> List readJsonList(final JSONArray result, Class<T> entityClass) {
    if (null == result)
        return null;

    List<T> list = new ArrayList<T>();
    Gson gson = new Gson();
    try {
        int size = result.length();
        for (int i = 0; i < size; i++) {
            list.add(gson.fromJson(result.getString(i), entityClass));
        }
    } catch (JSONException e) {
    }
    return list;
}

/**
 * 组成一个简单的json
 * @param id
 * @param name
 * @return
 */
public static JSONObject writeJsonSimple(int id, String name) {
    JSONObject json = new JSONObject();
    try {
        json.put("id", id);
        json.put("name", name);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return json;
}
public static JSONObject writeJson(int extendId, String tagValue,String tagText) {
    JSONObject json = new JSONObject();
    try {
        json.put("extendId", extendId);
        json.put("tagValue", tagValue);
        json.put("tagText", tagText);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return json;    

}

4、数据加载AsyncTask


public class HttpRequest extends AsyncTask<Void, Integer, Void> {

    private HttpParam params;
    private String url = null;
    private ApiRequest mCallBack = null;

    private String result = null;
    private String errInfo = null;

    /**
     * //表单方式: 
     * 0:application/x-www-form-urlencoded 
     * 1:multipart/form-data
     * 2:multipart/form-data,附件的ContentType传“image/jpeg”,含文件名
     */
    private int _formFlag = 0;

    public HttpRequest() {

    }

    /**
     * 构造方法
     * @param url 调用的URL
     * @param param 参数
     * @param formFlag 表单方式:0:application/x-www-form-urlencoded、1:multipart/form-data
     * @param request 接口回调
     */
    public HttpRequest(String url, HttpParam param, int formFlag, ApiRequest request) {
        this.url = url;
        this.mCallBack = request;
        this.params = param;
        this._formFlag = formFlag;
        this.result = "";
        this.errInfo = "";
    }

    /**
     * 执行POST调用
     */
    private void runReqPost() {
        try {
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 8000);
            HttpClient httpClient = new DefaultHttpClient(httpParams);

            HttpPost httpPost = new HttpPost(url);

            if (_formFlag == 0)
                httpPost.setEntity(params.getParamsPost());
            else if (_formFlag == 1) {
                httpPost.setEntity(params.getParamsPostFile());

                // 上传附件时,参数放在header里面!!!
                Map<String, Object> headers = params.getParams();
                if (null != headers && !headers.isEmpty()) {
                    for (Map.Entry<String, Object> entry : headers.entrySet()) {
                        String key = entry.getKey();
                        Object values = entry.getValue();

                        if (values instanceof String) {
                            httpPost.addHeader(key, (String) values);
                        }
                    }   
                }
            }

            HttpResponse httpResponse = httpClient.execute(httpPost);
            int code = httpResponse.getStatusLine().getStatusCode();
            Log.i("getStatusCode()", "------->" + code);

            if (code == HttpStatus.SC_OK) {
                result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
            } else {
                errInfo = "网络出错了";
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            errInfo = "客户端协议异常";
        } catch (IOException e) {
            e.printStackTrace();
            errInfo = "无法连接服务端";
        }
    }

    /**
     * AsyncTask方法重载 预执行 
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    /**
     * AsyncTask方法重载 后台异步执行
     * @return
     */
    @Override
    protected Void doInBackground(Void... params) {
        try {
            this.runReqPost();
        } catch (Exception e) {
            e.printStackTrace();
            errInfo = "接口异常";
        }

        return null;
    }

    /**
     * AsyncTask方法重载 在任务执行成功时回调
     */
    @Override
    protected void onPostExecute(Void voids) {
        if (null == mCallBack || (null != errInfo && !errInfo.equals(""))) {
            Log.e("info", "失败--->errInfo:" + errInfo);
            mCallBack.onResult(new BeanRequest().setError(errInfo));
            return;
        }

        BeanRequest bean = ApiPublic.readJsonUtil(result);
        if (!bean.isSuccess())
            Log.w("info", "失败--->" + result);
        else
            Log.v("info", "成功--->" + result);

        mCallBack.onResult(bean);

    }

    /**
     * AsyncTask方法重载 在任务成功取消时回调
     */
    @Override
    protected void onCancelled() {
        if (mCallBack != null) {
            Log.w("info", "失败--->任务已取消");
            mCallBack.onResult(new BeanRequest().setError("已取消"));
        }
    }
}

5、接口调用返回参数的实体类

public class BeanRequest {

    private boolean success = true;// 接口调用是否成功
    private String errInfo;// 错误原因
    private Object Data;// 获取成功,业务数据
    private String result;// 接口返回的数据

    public BeanRequest setError(String errInfo) {
        this.success = false;
        this.errInfo = errInfo;
        return this;
    }

    public BeanRequest setSucc(String result) {
        this.success = true;
        this.result = result;
        return this;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getErrInfo() {
        return errInfo;
    }

    public void setErrInfo(String errInfo) {
        this.errInfo = errInfo;
    }

    public Object getData() {
        return Data;
    }

    public void setData(Object data) {
        Data = data;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

}

6、网络请求参数储存类

/**
 * 网络请求参数存储类,以Map来存储
 */
public class HttpParam {
    private Map<String, Object> params = new HashMap<String, Object>();

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

    /**
     * 普通的参数
     * @param key
     * @param values
     */
    public void addParams(String key, Object values) {
        this.params.put(key, values);
    }

    /**
     * 带有附件的参数,只传一个附件
     * @param key
     * @param values
     */
    public void addParams(String key, File values) {
        this.params.put(key, values);
    }

    /**
     * 带有附件的参数,传多个附件
     * @param key
     * @param values
     */
    public void addParams(String key, Set<File> values) {
        this.params.put(key, values);
    }

    /**
     * Post方法调用时,取出参数
     * @return
     * @throws UnsupportedEncodingException
     */
    public HttpEntity getParamsPostFile() throws UnsupportedEncodingException {

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

        if (null == params || params.isEmpty()) {
            return multipartEntityBuilder.build();
        }

        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object values = entry.getValue();
            if (values instanceof File) {
                multipartEntityBuilder.addBinaryBody(key, (File) values);
            } else if (values instanceof Set) {
                for (File file : (Set<File>) values) {
                    multipartEntityBuilder.addBinaryBody(key, (File) file);
                }
            }
        }

        return multipartEntityBuilder.build();
    }

    /**
     * 使用application/x-www-form-urlencoded表单的方式传递参数
     * @return
     */
    public HttpEntity getParamsPost() {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        JSONObject jsonObj = new JSONObject();
        try {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                Object values = entry.getValue();
                if (values instanceof JSONArray) {
                    jsonObj.put(key, (JSONArray) values);
                } else {
                    jsonObj.put(key, values);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        nameValuePairs.add(new BasicNameValuePair("param", jsonObj.toString()));
        Log.i("wocaonima", "参数的值为:" + jsonObj);

        HttpEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return entity;
    }

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。