首页 > 解决方案 > onResponse(String response) try { JSONObject jsonObject=new JSONObject(response);java.lang.String 无法转换为 JSONObject

问题描述

我找不到答案。试过很多网站,包括这个。我想知道问题出在哪里。

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

这是我的安卓代码:-

    StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_LOGIN,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {

                    try {

                        JSONObject jsonObject=new JSONObject(response);

                        String success=jsonObject.getString("success");

                        JSONArray jsonArray=jsonObject.getJSONArray("login");

                        if (success.equals("1")){
                            for (int i=0;i<jsonArray.length();i++) {
                                JSONObject object=jsonArray.getJSONObject(i);

                                String uname=object.getString("username").trim();
                                String email=object.getString("email");

                                Toast.makeText(MainActivity.this, "Login Successful!!! \n Your Name: "+uname+"\nYour Email: "+email, Toast.LENGTH_SHORT).show();
                                loading.setVisibility(View.GONE);
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this," Error!!"+e.toString(),Toast.LENGTH_LONG).show();
                        loading.setVisibility(View.GONE);
                        signin_btn.setVisibility(View.VISIBLE);
                    }

                }
            },

日志猫

2019-09-06 19:40:37.264 7944-7944/com.example.project W/System.err: org.json.JSONException: java.lang.String 类型的值连接无法转换为 JSONObject 2019-09-06 19:40:37.264 7944-7944/com.example.project W/System.err: 在 org.json.JSON.typeMismatch(JSON.java:111) 2019-09-06 19:40:37.264 7944-7944/com .example.project W/System.err: at org.json.JSONObject.(JSONObject.java:160) 2019-09-06 19:40:37.264 7944-7944/com.example.project W/System.err: at org.json.JSONObject.(JSONObject.java:173)

标签: javaandroidjsonphpmyadminlocalhost

解决方案


正如异常所暗示的,response字符串不能转换为JSONObject

public JSONObject(java.lang.String source) throws JSONException

抛出:JSONException- 如果源字符串中存在语法错误或重复键。

来自:http ://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-

确保您的response字符串(从 POST 请求中获得URL_LOGIN)确实是一个有效的 JSON 字符串。要么编写包含系统托管的端到端测试,要么使用URL_LOGINPostman 等客户端手动测试系统服务URL_LOGIN是否按照应用程序的请求工作。


推荐阅读