org.json.JSONException:值类型java.lang.String的连接无法转换为JSONObject

时间:2016-03-22 16:57:00

标签: java android mysql json android-studio

我正在为我的应用程序编写一个登录函数,我突然开始收到此错误:org.json.JSONException: Value Connection of type java.lang.String cannot be converted to JSONObject我不记得在这里修改代码并且之前曾经工作过。当我开始在android studio上使用调试模式时,它突然停止工作。

以下是我的代码片段,错误似乎位于标有/ * ERROR * /的两行上:

private String loginUrl = "http://10.0.2.2/user/login.php";

login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            request = new StringRequest(Request.Method.POST, loginUrl, new Response.Listener<String>() /*ERROR*/ {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response); /*ERROR*/
                        if (jsonObject.names().get(0).equals("success")) {
                            Toast.makeText(getApplicationContext(), jsonObject.getString("success"), Toast.LENGTH_SHORT).show();
                            email.setText("");
                            password.setText("");
                            Log.d("test", "Going to Main.class");
                            startActivity(new Intent(MainActivity.this, Main.class));
                            //setContentView(R.layout.activity_main);
                        } else {
                            Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> parameters = new HashMap<String, String>();
                    parameters.put("email", email.getText().toString());
                    parameters.put("password", password.getText().toString());
                    return parameters;
                }
            };
            requestQueue.add(request);
        }
    }); 

2 个答案:

答案 0 :(得分:0)

似乎response对象格式不正确,无法转换为JSON对象。 I've created a fiddle to demonstrate.

答案 1 :(得分:0)

org.json.JSONObject(String json)使用JSON字符串中的名称/值映射创建新的JSONObject

此异常表示您的response参数不包含有效的JSON