Volley的响应处理

Nit*_*ish 8 android json android-volley

Volley在我的项目中用于处理网络请求.这是JSON我的服务器返回的示例

JSON对象响应

{"code":"success", "data":{"some data"}}
Run Code Online (Sandbox Code Playgroud)

JSON数组响应

{"code":"success", "data":["some data"]}
Run Code Online (Sandbox Code Playgroud)

发生某些验证错误或任何其他错误时,服务器返回以下响应:

{"code":"failed", "error":"Access denied"}
Run Code Online (Sandbox Code Playgroud)

问题在于解析数据.当请求成功onResponseResponseListener,我只需获取data密钥的内容.在哪里,我期待的结果与我上面发布的相同.我不知道为什么Volley只返回内容data而不是完整内容JSON.我Volley之前也用过.但从未遇到过这类问题.

解析代码:

private void getOnboardingCategories() {
    Response.Listener<JSONArray> responseListener = new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {
            Log.d(LOG_TAG, "CATEGORY RESPONSE: " + response.toString());
            if (response != null) {
                int dataLength = response.length();
                for (int i = 0; i < dataLength; i++) {
                    JSONObject jObject = response.optJSONObject(i);
                    if (jObject != null) {
                        CategoryType2 categoryType2 = new CategoryType2();
                        categoryType2.set_id(jObject.optString("_id"));
                        categoryType2.setName(jObject.optString("name"));
                        categoryType2.setApp_icon_data(jObject.optString("thumbnail_data"));
                        categories.add(categoryType2);
                    }
                }
            }
            if (isVisible())
                sellAdapter.notifyDataSetChanged();
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            Util.errorHandler(error, ctx);
        }
    };

    JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Method.GET, url,
            null, responseListener, errorListener);
    MyApplication.getInstance().addToRequestQueue(jsonObjectRequest, "onboarding");
}
Run Code Online (Sandbox Code Playgroud)

成功回应:

{
   code: "success",
   data: [
             {
                 _id: "55c06b05a3e0041a73cea744",
                 name: "Test Category 1",
                 thumbnail_data: "",
             },
             {
                 _id: "55c06b16a3e0046108cea744",
                 name: "Test Category 2",
                 thumbnail_data: "",
             }
         ]
}
Run Code Online (Sandbox Code Playgroud)

onResponseResponseListener,我得到这样的数据:

[
    {
        _id: "55c06b05a3e0041a73cea744",
        name: "Test Category 1",
        thumbnail_data: "",
    },
    {
        _id: "55c06b16a3e0046108cea744",
        name: "Test Category 2",
        thumbnail_data: "",
    }
]
Run Code Online (Sandbox Code Playgroud)

发生错误时,服务器返回此响应:

{"code":"failed", "error":"error_msg"}
Run Code Online (Sandbox Code Playgroud)

因此,Volley抛出ParseException预期JSONArray.我需要向用户显示错误消息.早些时候,我正在使用AsyncTask,我在那里处理错误.但是,Volley我面临困难.我调查了一下VolleyError,但没有任何线索.

更新1

private void getOnboardingCategories() {
    showSpinnerDialog(true);
    Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d(LOG_TAG, "CATEGORY RESPONSE: " + response.toString());
            hideSpinnerDialog();
            String code = response.optString("code");
            if (code.equals("success")) {
                if (response != null) {
                    JSONArray dataArray = response.optJSONArray("data");
                    int dataLength = dataArray.length();
                    for (int i = 0; i < dataLength; i++) {
                        JSONObject jObject = dataArray.optJSONObject(i);
                        if (jObject != null) {
                            CategoryType2 categoryType2 = new CategoryType2();
                            categoryType2.set_id(jObject.optString("_id"));
                            categoryType2.setName(jObject.optString("name"));
                            categoryType2.setApp_icon_data(jObject.optString("app_icon_data"));
                            categories.add(categoryType2);
                        }
                    }
                }
            }
            if (isVisible())
                sellAdapter.notifyDataSetChanged();
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            Util.errorHandler(error, ctx);
        }
    };

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET, url,
            null, responseListener, errorListener);
    MyApplication.getInstance().addToRequestQueue(jsonObjectRequest, "onboarding");
}
Run Code Online (Sandbox Code Playgroud)

更新 此问题与此无关Volley.在服务器端有问题grt gzip压缩.我打算投票结束这个问题.

ρяσ*_*я K 5

但是,当发生错误时,我在发出JSONArray请求时会得到Parse异常

使用JSONObject.has()JSONObject.isNull()在解析json之前检查json响应中存在哪个键.

例如:

JSONObject jsonObject=new JSONObject(<server_response_string>);
  if(jsonObject.has("data") && !jsonObject.isNull("data"))
  {
    // get data JSONArray from response
  }else{
     // get message using error key
   }
Run Code Online (Sandbox Code Playgroud)