Cannot Receive JSONobject on JSONObjectRequest using Volley

时间:2016-08-31 12:12:47

标签: android json android-volley

This is my code for requesting the JSONObject. While working with String request it worked perfectly but i need JSONObject.

    Map<String, String> params = new HashMap<String, String>();
    params.put("username", username);
    params.put("password", password);
    params.put("request", "login");

    JSONObject jsonObj = new JSONObject(params);

    String url="http://example.com/android/login.php";
    JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url,jsonObj,
            new Response.Listener<JSONObject>()
            {


                @Override
                public void onResponse(JSONObject response) {
                    // response
                   // JSONObject json = JSONObject.toJson(response);
                   // Toast.makeText(Login.this, "Your ID is ."+response, Toast.LENGTH_LONG).show();

                    //Log.d("Response", response.toString());

                    Intent r = new Intent(Login.this,Cus_home.class);
                    startActivity(r);

                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    Log.d("Error.Response", error.toString());
                }
            }
    );

    mRequestQueue.add(postRequest);

On checking the API output the output is : [{"id":"77","type":"1"}]

But after running the android code, I get this

Error.Response: com.android.volley.ParseError: org.json.JSONException: End of input at character 1 of  

Any help help is really appreciated

1 个答案:

答案 0 :(得分:0)

您将返回无效的JSON对象。您正在返回JSON字符串而不是对象。

  

JSON对象写在花括号内。例如   {“firstName”:“John”,“lastName”:“Doe”}`

你的onResonse方法看起来像这样

public void onResponse(JSONObject response) {
                    Log.d("response", response.optString("id") + " " +
                            response.optString("type"));

}