Fehler beim Parsen der Daten org.json.JSONException: Typ java.lang.Zeichenfolge kann nicht konvertiert werden JSONObject

Derzeit meine PHP-Datei, die verwendet wird, um eine Schnittstelle zwischen dem MySQL server und meine Android-app sieht wie folgt aus:

<?php
//array for JSON response
$response = array();

if (isset($_GET['porfileID'])) {
     $ID = $_GET['porfileID'];

    //include db connect class
    require_once __DIR__ . '/db_connect.php';

    //connecting to db
    $db = new DB_CONNECT();

    //get all products from products table
    $result = mysql_query("SELECT * FROM profiles_profilelists WHERE ProfileID = '$ID'") or die(mysql_error());

    //check for empty result
    if (mysql_num_rows($result) > 0) {
        //looping through all results
        //products node
        $response["lists"] = array();

        while ($row = mysql_fetch_array($result)) {
        //temp user array
        $lists = array();
        $lists["ProfileListID"] = $row["ProfileListID"];
        $lists["ProfileListName"] = $row["ProfileListName"];

        //push single product into final response array
        array_push($response["lists"], $lists);
        }
        //success
        $response["success"] = 1;

        //echoing JSON response
        echo json_encode($response);
    } else {
        //no products found
        $response["success"] = 0;
        $response["message"] = "No products found";

        //echo no users JSON
        echo json_encode($response);
    }
} else {
    //required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    //echoing JSON response
    echo json_encode($response);
}
?>

Dies funktioniert gut, aber wenn ich hinzufügen:

$result2 = mysql_query("SELECT * FROM profiles_profilelistitems WHERE ProfileListID = ".$row["ProfileListName"]) or die(mysql_error());

$lists["ListCount"] = mysql_num_rows($result2);

Meine Php so wie es aussieht:

<?php


//array for JSON response
$response = array();

if (isset($_GET['porfileID'])) {
     $ID = $_GET['porfileID'];

    //include db connect class
    require_once __DIR__ . '/db_connect.php';

    //connecting to db
    $db = new DB_CONNECT();

    //get all products from products table
    $result = mysql_query("SELECT * FROM profiles_profilelists WHERE ProfileID = '$ID'") or die(mysql_error());

    //check for empty result
    if (mysql_num_rows($result) > 0) {
        //looping through all results
        //products node
        $response["lists"] = array();

        while ($row = mysql_fetch_array($result)) {
        //temp user array
        $lists = array();
        $lists["ProfileListID"] = $row["ProfileListID"];
        $lists["ProfileListName"] = $row["ProfileListName"];

        $result2 = mysql_query("SELECT * FROM profiles_profilelistitems WHERE ProfileListID = ".$row["ProfileListName"]) or die(mysql_error());

        $lists["ListCount"] = mysql_num_rows($result2);

        //push single product into final response array
        array_push($response["lists"], $lists);
        }
        //success
        $response["success"] = 1;

        //echoing JSON response
        echo json_encode($response);
    } else {
        //no products found
        $response["success"] = 0;
        $response["message"] = "No products found";

        //echo no users JSON
        echo json_encode($response);
    }
} else {
    //required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    //echoing JSON response
    echo json_encode($response);
}
?>

Ich am Ende mit dem oben genannten Fehler.
Die komplette Spur ist:

09-03 17:05:57.836: E/JSON Parser(675): Error parsing data org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONObject
09-03 17:05:59.617: E/AndroidRuntime(675): FATAL EXCEPTION: AsyncTask #1
09-03 17:05:59.617: E/AndroidRuntime(675): java.lang.RuntimeException: An error occured while executing doInBackground()
09-03 17:05:59.617: E/AndroidRuntime(675):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-03 17:05:59.617: E/AndroidRuntime(675):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.lang.Thread.run(Thread.java:856)
09-03 17:05:59.617: E/AndroidRuntime(675): Caused by: java.lang.NullPointerException
09-03 17:05:59.617: E/AndroidRuntime(675):  at com.test.app.MyLists$LoadAllLists.doInBackground(MyLists.java:267)
09-03 17:05:59.617: E/AndroidRuntime(675):  at com.test.app.MyLists$LoadAllLists.doInBackground(MyLists.java:1)
09-03 17:05:59.617: E/AndroidRuntime(675):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-03 17:05:59.617: E/AndroidRuntime(675):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-03 17:05:59.617: E/AndroidRuntime(675):  ... 5 more

Den code, der die trace-links innerhalb der app:

protected String doInBackground(String... args) {
            //Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("porfileID", Integer.toString(userID)));
            //getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            //Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                //Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    //products found
                    //Getting Array of Products
                    products = json.getJSONArray("lists");
                    productsList.clear();
                    //looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        //Storing each json item in variable
                        String id = c.getString("ProfileListID");
                        String name = c.getString("ProfileListName");
                        //String count = c.getString("ListCount");
                        //creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        //adding each child node to HashMap key => value
                        map.put("ProfileListID", id);
                        map.put("ProfileListName", name);

                        //adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

Und schließlich die json-parser, den ich verwende

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    //constructor
    public JSONParser() {

    }

    //function get json from url
    //by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        //Making HTTP request
        try {

            //check for request method
            if(method == "POST"){
                //request method is POST
                //defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                //request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        //try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        //return JSON String
        return jObj;

    }
}
Haben Sie versucht, Blick auf das format der JSON-Objekt zurückgegeben wird, die von php zu sehen, ob es richtig ist?
das seltsame ist, es funktioniert bevor ich die zwei anderen Linien der PHP-dies ist sicherlich nicht das ändern des formats? oder bin ich da falsch
Ich denke, es könnte da Sie hinzufügen, um das Antwort-array... anschauen kann man sich die Antwort, die Sie erhalten auf der Android-Seite und verwenden Sie eine JSON-verifier (jsonlint.com) zu überprüfen, gibt es keine Probleme mit der Formatierung
bitte posten Sie Ihre json-string Antwort

InformationsquelleAutor Zac Powell | 2013-09-03

Schreibe einen Kommentar