获取“ org.json.JSONArray无法转换为JSONObject”

时间:2018-12-22 21:46:16

标签: android json android-volley

我正在尝试使用凌空库发布json方法从android应用程序中的json格式的服务器中获取数据。但是每次都会得到一个'org.json.JSONArray无法转换为JSONObject'。

这是错误:

Error: org.json.JSONException: Value [{"status":"Success","code":1313,"msg":"Request completed successfully"}] of type org.json.JSONArray cannot be converted to JSONObject.

那是我的代码:

            RequestQueue requestQueue = Volley.newRequestQueue(this);
            JSONObject jsonObject = new JSONObject();

            try {
                jsonObject.put("auth", "---------");
                jsonObject.put("request", "Login");
                jsonObject.put("Name", "raky");
                jsonObject.put("Email", "exp@a.com");
            } catch (JSONException e) {
                e.printStackTrace();
            }


            String url = "http://my.website_name.com/";
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {

                            Log.d("VOLLEY", response.toString());
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d("ERROR.VOLLEY", error.getMessage());

                        }

                    });

            jsonObjectRequest.setTag(1);
            requestQueue.add(jsonObjectRequest);

2 个答案:

答案 0 :(得分:1)

这里的问题是您的网站响应正文对象是JSONArray

[
    {
        "status": "Success",
        "code": 1313,
        "msg": "Request completed successfully"
    }
]

因此您会得到例外,因为在响应处理程序中您需要JSONObject,并且无法将JSONArray强制转换为JSONObject

您的服务器(网站)必须返回给您的是 root JSONObject,然后在其节点树中可以有JSONArray,但是根必须是JSONObject

因此修复服务器端代码,使其返回:

    {
        "status": "Success",
        "code": 1313,
        "msg": "Request completed successfully"
    }

答案 1 :(得分:0)

您的响应是一个数组, 您可以使用诸如Postman之类的api测试工具来测试您的api,看看您从api中得到了什么,也可以使用StringRequest代替JsonObjectRequest,通过这种方法,您可以获取任何类型的响应并转换为所需的类型

相关问题