php - org.json.JSONException : Value Connected of type java. lang.String 无法转换为 JSONObject

标签 php mysql json android-studio android-volley

我正在尝试列出来自外部 SQL 数据库的挑战。我有一个大问题。我正在从 MySQL 检索数据,但在 JSONObject 上遇到错误。我已经尝试了几个小时,所以如果有人能指出我正确的方向 - 我一直在使用本教程作为引用 https://www.simplifiedcoding.net/android-spinner-example-to-load-json-using-volley/

PHP 文件 - Challengeall.php

<?php

$servername = "localhost";
$username = "USER";
$password = "PASS";
$dbname  ="android_api";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

//$stmt = $dbconn->conn->prepare("SELECT * FROM challenges") or die(mysql(mysql_error()));

$stmt = "SELECT * FROM challenges";
$result = $conn->query($stmt);
$results = array();

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
            array_push($results,array(  
                'unique_id'=>$row["unique_id"],
                'title'=>$row["title"]
            ));    
      //  echo "id: " . $row["id"]. " - unique id: " . $row["unique_id"]. " - title: " . $row["title"]. "<br>";  
    }
    echo json_encode(array('results'=>$results));

} else {
    echo "0 results";
}
$conn->close();

?>

字段

String url = "http://myLocalIPConnectsFine/android_login_api/challengesall.php";
public static final String JSON_ARRAY = "results";
private JSONArray challengeResult;

ChallengeListActivity - 方法 getData

private void getData() {
        //Tag used to cancel the request
        String tag_string_req = "req_challenge";
        Log.i("M4: " + TAG + ":- " + STEP, Thread.currentThread().getStackTrace()[2].getMethodName());

        StringRequest strReq = new StringRequest(
                url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.i("M6: " + TAG + ":- " + STEP, Thread.currentThread().getStackTrace()[3].getMethodName());

                Log.d(TAG, "Login Response: " + response.toString());
                JSONObject j = null;

                try {
                    //Parsing the fetched Json String to JSON Object
                    j = new JSONObject(response);  //!!GOES TO CATCH EXCEPTION!!! 

                    //Storing the Array of JSON String to our JSON Array
                    challengeResult = j.getJSONArray(JSON_ARRAY);  //DOES NOT GET HERE!! :((

                    // TODO: Now store the user in SQLite for loop

                    //Calling method getStudents to get the students from the JSON Array
                    getChallenges(challengeResult);
                    // }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) ;
        // Adding request to request queue
        //  AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(strReq);
    }

错误消息

07-25 16:54:09.900 8134-8134/boo.famvsfam D/STEPS:  ChallengeListActivity: Login Response: Connected successfully{"result":[{"unique_id":"57933c641237d4.96974874","title":"23072016"},{"unique_id":"57901472464398.57585757","title":"hayley"},{"unique_id":"5790142623de26.96306456","title":"nbppp"},{"unique_id":"5790133be27ca1.05397869","title":"bopo"},{"unique_id":"57900e98bc4dd2.35778585","title":"howdie"},{"unique_id":"57900dfb7fca74.47168154","title":"BOOO"},{"unique_id":"579006b05dfda0.42529504","title":"BOOO"},{"unique_id":"578f7e139835d2.76955191","title":"ghhg"},{"unique_id":"578f71b8ef5693.01745921","title":"howdie"},{"unique_id":"578f71b50c7407.91547319","title":"howdie"},{"unique_id":"578f4d212bcf41.00048708","title":"heloorout"},{"unique_id":"578f4b794281e1.43679386","title":"heloorout"},{"unique_id":"578ed1338cdfd2.06152669","title":"BOO"},{"unique_id":"578e72b5920bd9.67743323","title":"BOO3"},{"unique_id":"578e7168921b95.27637073","title":"BOO4566677777"},{"unique_id":"578e7161f32df1.06784020","title":"BOO"},{"unique_id":"578e0f7564c5c6.94428032","title":"lalalala"},{"unique_id":"578e0fbb8f95d8.48337399","title":"ghhhh"},{"unique_id":"578f5912ac55f4.71485786","title":"boo"},{"unique_id":"578f54c82c81c5.06156083","title":"jjjj"},{"unique_id":"578f53c251fb73.32146656","title":"ccc"},{"unique_id":"578f53c22ee9e2.44032439","title":"ccc"},{"unique_id":"578f533a759556.38700080","title":"ccc"},{"unique_id":"578f51beafcdd6.40560734","title":"hjjj"},{"unique_id":"578f51b3adc9c6.53224544","title":"hjjj"},{"unique_id":"578d82ebba7e82.61976731","title":"rhtyhrrh"},{"unique_id":"578d71ad826874.17496613","title":"FHGHHH"},{"unique_id":"578d6d659605d7.58107965","title":"BOO5003"},{"unique_id":"578d6d555f0774.18558468","title":"BOO500000"},{"unique_id":"57933ca3e56379.52606857","title":"23072016-1"},{"unique_id":"57933cb6746b58.44233261","title":"23072016-2"},{"unique_id":"579356c1f37c94.92512350","title":"AChallenge"},{"unique_id":"5793571d9238c4.62232112","title":"challenge"},{"unique_id":"5793571da78159.61806596","title":"challenge"},{"unique_id":"57935884e7bcf2.72928133","title":"achallenge"},{"unique_id":"579366336a78a5.36422777","title":"boooo"},{"unique_id":"579366dfe75647.32061097","title":"boooo"},{"unique_id":"57936f03c884b0.46671632","title":"fggggg"},{"unique_id":"57936f9be26a56.60274804","title":"boo"},{"unique_id":"57936fa0adf927.36072785","title":"boo"},{"unique_id":"57936fc695b686.27459827","title":"boo"},{"unique_id":"57937003032435.98039444","title":"boo"},{"unique_id":"579370f3b54f01.71840531","title":"boo"},{"unique_id":"5793785f5d6ff0.67364375","title":"booooo"},{"unique_id":"579379447425d8.12021062","title":"booooo"}]}
07-25 16:54:42.915 8134-8134/boo.famvsfam W/System.err: org.json.JSONException: Value Connected of type java.lang.String cannot be converted to JSONObject
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at boo.famvsfam.controller.ChallengeListActivity$4.onResponse(ChallengeListActivity.java:256)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at boo.famvsfam.controller.ChallengeListActivity$4.onResponse(ChallengeListActivity.java:245)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:67)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at android.os.Looper.loop(Looper.java:148)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-25 16:54:42.916 8134-8134/boo.famvsfam W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我认为我不需要再发布代码 - 问题似乎出在尝试之后的 j = new JSONObject(response); 上。我是一个非常新的 JSON,但这个问题已经存在超过一天了:( 我想在那之后我会没事的,但是无论我尝试什么方法,我都会遇到这个问题(并且我已经尝试了很多教程和问题/答案)有人可以指出我哪里出错了。这是我第一次尝试 JSON。

最佳答案

实例化 JSONObject 时您需要传递实际的字符串响应:

例如:JSONObject obj = new JSONObject("结果":[{"unique_id":"57933c641237d4.96974874","title":"23072016"},{"unique_id":"57901472464398.57585757","标题":"海莉"}]");

鉴于 response.toString() 为您提供了字符串,您应该执行以下操作:

JSONObject j = new JSONObject(response.toString());

P.S:如果您没有在 php 中设置内容类型,我认为您需要这个:

<?
header('Content-Type: application/json');
$servername = "localhost";
$username = "USER";
$password = "PASS";
$dbname  ="android_api";
....

关于php - org.json.JSONException : Value Connected of type java. lang.String 无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38573539/

相关文章:

php - MySQL:4 表 "has-many-through"加入?

php - 过滤时长

javascript - 如何使用 PHP 处理 Controller 的 XMLhttp 请求

javascript - 如何从 JSON 对象获取元素值并首先将其转换为 HTML,然后再转换为 String

javascript - 创建 Javascript 对象时出错

python - 使用 Python 3 检查 JSON 键是否为空的条件语句

php - 在旧的 apache 安装上使用 PHP 5.3

php - 从表中选择日期 - strtotime?

MySql 替换最后一个/之后的内容

php - 使用 PHP 和 HTML 表单更新 SQL 数据库中的数据