Android Json parsing string cannot be converted to json object error

Viewed 324

I want to send parameters such as username and password.

I got an error like String cannot be converted to jsonobject.

I dont know what this happening.Anyone pls help me my code is:

        JSONObject obj=new JSONObject();
            try{
            obj.put("username","test");
                obj.put("password","test");
            } catch (JSONException e) {
            }

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                urlJsonObj, obj, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                } catch (JSONException e) {
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }

        });
        // Adding request to request queue
      AppController.getInstance().addToRequestQueue(jsonObjReq,json_obj_req);
    }
2 Answers

It looks like your response is actually a string and not a json object i.e. {"object":"value"} but rather "object:value". You need to sniff your response via either Stetho, Fiddler or reenact your request via Postman (or Fiddler)

======================

This doesn't answer your question, but this will help you tremendously and make your life easier.

Highly recommend using Gson and Retrofit to make HTTP requests and parse Gson objects easily.

https://github.com/google/gson

http://square.github.io/retrofit/

There is nothing wrong with the way you are creating JSONObject and putting values in it. Make sure the response received is Json, because your onResponse method accepts JSONObject. You could be receiving String value as response, which could not be converted to JSONObject.

Related