Android:如何从使用Volley的方法返回异步JSONObject?

时间:2015-09-03 12:11:39

标签: android json android-asynctask android-volley

我正试图以下列方式取回JSON对象:

JSONObject jsonObject = http.makeRequest("GET", "https://api.twitter.com/1.1/search/tweets.json", null);

处理所有HTTP请求的一般方法如下

public void makeRequest(String method, String url, Array params) {

    // Request a string response from the provided URL.
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(getRequestMethod(method),
            url,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    processResponse(Constants.Global.SUCCESS, null, response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    try {
                        mStatusCode = error.networkResponse.statusCode;
                        VolleyLog.d(Constants.Global.ERROR, "Error: " + error.getMessage());
                        Logger.e(error.getMessage());
                    } catch (Exception e) {
                        Logger.e(e.getMessage());
                        mStatusCode = 0;
                    }
                    Logger.e(mStatusCode.toString());
                    processResponse(Constants.Global.ERROR, mStatusCode, null);
                }
            });
    // Add tag to request for bulk cancelling
    //jsonObjReq.setTag()
    queue.add(jsonObjReq);
}

处理JSON结果的方法如下:

private JSONObject processResponse(String resultState, Integer httpStatusCode, JSONObject responseData) {
        try {
            // First check that result state is error or the success
            if (resultState.equals(Constants.Global.SUCCESS)) {
                Logger.i("Response is success");
                Logger.i(responseData.toString());
                //TODO: ADD SUCCESS OBJECT CREATION
            }
            if (resultState.equals(Constants.Global.ERROR)) {
                Logger.e("Response is error");
                //TODO: ADD ERROR HANDLING AND ERROR OBJECT CREATION
            }

        } catch(Exception e) {
            e.printStackTrace();
            Logger.e(e.getMessage());
        }
        return responseData;
    }

我想问一下如何以异步方式返回JSONObject(第一个代码片段)。

使用Volley库处理所有请求。

非常感谢您的任何建议。

1 个答案:

答案 0 :(得分:6)

征求意见

  

我认为Volley会自动提供异步。所以我需要   知道如何将JSON数据放入第一个片段

IMO,您可以尝试以下方式代替第一个代码段(当然,您可以通过FILEVAR请求替换/* Create sample data */ data test; input color $ num; datalines; blue 1 blue 2 blue 3 green 4 green 5 red 6 red 7 red 8 ; data _null_; length fname $30.; set test; by color; if first.color then count+1; fname="C:\TEMP\file" || trim(left(put(count,8.)))||".txt"; file dummy filevar=fname; put color num count; run; 请求):

JSONArray

JSONObject的正文如下:

VolleyResponseListener listener = new VolleyResponseListener() {
            @Override
            public void onError(String message) {
                // do something...
            }

            @Override
            public void onResponse(Object response) {
                // do something...
            }
        };

makeJsonArrayRequest(context, Request.Method.POST, url, requestBody, listener);

makeJsonArrayRequest接口如下:

    public void makeJsonArrayRequest(Context context, int method, String url, String requestBody, final VolleyResponseListener listener) {
        JSONObject jsonRequest = null;        
        try {
            ...
            if (requestBody != null) {
                jsonRequest = new JSONObject(requestBody);
            }
            ...
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                listener.onResponse(jsonArray);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error.toString());
            }
        });

        // Access the RequestQueue through singleton class.
        MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
    }