Rakesh Kumar
Rakesh Kumar

Reputation: 79

Getting ''org.json.JSONArray cannot be converted to JSONObject''

I'm trying to get data from my server in json format in my android application using volley library post json method. But everytime gets a 'org.json.JSONArray cannot be converted to JSONObject'.

This the error:

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

And that's my code:

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

            try {
                jsonObject.put("auth", "---------");
                jsonObject.put("request", "Login");
                jsonObject.put("Name", "raky");
                jsonObject.put("Email", "[email protected]");
            } 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);

Upvotes: 0

Views: 510

Answers (2)

shadowsheep
shadowsheep

Reputation: 15002

The prolem here is that your website response body object is a JSONArray

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

So you get the exception because in the response handler you want a JSONObject and you can't cast a JSONArray to a JSONObject.

What your server (website) have to return to you is a root JSONObject and then in its node tree it could have JSONArray, but the root must be a JSONObject.

So fix your server side code so that it returns:

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

Upvotes: 1

Samad
Samad

Reputation: 1832

Your response is an Array, you can test your api with some api test tools like Postman and see what you get from api, also you can use StringRequest instead of JsonObjectRequest, by this method you can get any type of response and converted to the type you need

Upvotes: 0

Related Questions