【问题标题】:Getting ''org.json.JSONArray cannot be converted to JSONObject''获取 ''org.json.JSONArray 无法转换为 JSONObject''
【发布时间】:2018-12-22 21:46:16
【问题描述】:

我正在尝试使用 volley 库 post 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);

【问题讨论】:

  • 从您的网站返回了什么?您能否也发布原始响应正文?
  • 错误添加,请检查
  • 它返回包裹在方括号 [{your json body}] 中的 JSON。删除它们:{your json body} 或用括号括起来。重要的是,您的根主体 JSON 主体元素是 JSONObject 而不是 JSONArray。

标签: android json android-volley


【解决方案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"
    }

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-06-30
      • 2018-05-12
      • 1970-01-01
      • 2014-02-03
      • 2017-01-03
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多