如何在Volley中获取JSONObject服务器响应 [英] How to get the JSONObject server response in Volley

查看:75
本文介绍了如何在Volley中获取JSONObject服务器响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected JSONObject executeGet(String URL) throws CloudAppException {
    JSONObject response = new JSONObject();
    JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, URL, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject serverResponse) {
                    try {
                        response = serverResponse;
                        VolleyLog.v("Response:%n %s", serverResponse.toString(4));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    });

    RequestHandler.addToRequestQueue(req);

    return response;
}

理想情况下,我想自己解析响应,但是我不知道如何获取executeGet方法以返回服务器响应.

Ideally, I want to parse the response on my own, but I'm blanking on as to how to get the executeGet method to return the server response.

推荐答案

您需要扩展请求类,并在您的自定义请求类中覆盖parseNetworkResponse方法并进行自己的解析.

You need to extend the request class and in your custom request class override the parseNetworkResponse method and do your own parsing.

这里是一个示例:

public class CustomRequest extends Request {
    // the response listener
    private Response.Listener listener;

    public CustomRequest(int requestMethod, String url, Response.Listener responseListener, Response.ErrorListener errorListener) { 
        super(requestMethod, url, errorListener); // Call parent constructor
        this.listener = responseListener;
    }

    // Same as JsonObjectRequest#parseNetworkResponse
    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    public int compareTo(Request other) {
        return 0;
    }

    @Override
    protected void deliverResponse(Object response) {
        if (listener!=null)
            listener.onResponse(response);      
    }        
}

这篇关于如何在Volley中获取JSONObject服务器响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆