0

我正在开发一个 Android 应用程序,我需要从我的 php 论坛中检索主题列表,但是当我运行代码时,我得到了这个我无法弄清楚的错误

03-18 09:11:43.221: E/JSON(286): <br />
03-18 09:11:43.221: E/JSON(286): <b>Parse error</b>:in  <b>C:\xampp\htdocs\android_login_api\include\list_of_topics.php</b> on line <b>26</b><br />
03-18 09:11:43.322: E/JSON Parser(286): Error parsing data org.json.JSONException: Value <br of     type java.lang.String cannot be converted to JSONObject

这是我的 php

<?php

/*
 * Following code will list all the products
 */

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

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

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

// get all products from products table
if(isset($_GET['parent']))
{
    $id = intval($_GET['parent']);}
$result = mysql_query("select t.id, t.title, u.username as author,  from topics as t  left join user as u where t.parent="'.$id.'" and t.id2=1 group by t.id order by t.timestamp2 desc');
") or die(mysql_error());

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

    while ($row = mysql_fetch_array($result)) {
    // temp user array
    $topic = array();
    $topic["tid"] = $row["t.id"];
    $topic["name"] = $row["t.title"];
    $topic["author"] = $row["u.username"];


    // push single product into final response array

    array_push($response["topics"], $topic);
    echo json_encode($response);
    }
    // success
    $response["success"] = 1;

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

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

这是 JSON 解析器类,我有 2 个 JSONOBJECT 一个用于用户 reg&login,第二个用于主题列表

package com.example.androidhive.library;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // 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();

        } 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();
            Log.e("JSON", json);
        } 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;

    }

     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();
            Log.e("JSON", sb.toString());
            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;

        }


}

这是来自 Android 端的 .java 文件

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.androidhive.library.JSONParser;




public class Topics_list extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> TopicsList;

// url to get all products list
private static String url_all_topics = "http://10.0.2.2/android_login_api/include/list_of_topics.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TOPICS = "topics";
private static final String TAG_TOPICSID = "t.id";
private static final String TAG_TOPICTITLE = "t.title";
private static final String TAG_TOPICAUTHOR = "u.username";

// products JSONArray
JSONArray topics = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.topics_list);

// Hashmap for ListView
TopicsList = new ArrayList<HashMap<String, String>>();

// Loading products in Background Thread
new LoadAllTopics().execute();

// Get listview
ListView lv = getListView();

// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // getting values from selected ListItem
    String tid = ((TextView) view.findViewById(R.id.tid)).getText()
        .toString();
    }
   });

   }

    /*// Starting new intent
    Intent in = new Intent(getApplicationContext(),
        EditProductActivity.class);
    // sending pid to next activity
    in.putExtra(TAG_PID, pid);

    // starting new activity and expecting some response back
    startActivityForResult(in, 100);
    }
});

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
    // if result code 100 is received
    // means user edited/deleted product
    // reload this screen again
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

}*/

/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllTopics extends AsyncTask<String, String, String> {

/**
 * Before starting background thread Show Progress Dialog
 * */
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(Topics_list.this);
    pDialog.setMessage("Loading products. Please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}

/**
 * getting All products from url
 * */
protected String doInBackground(String... args) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // getting JSON string from URL
    JSONObject json = jParser.makeHttpRequest (url_all_topics, "GET", params);

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

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

    if (success == 1) {
        // products found
        // Getting Array of Products
        topics = json.getJSONArray(TAG_TOPICS);

        // looping through All Products
        for (int i = 0; i < topics.length(); i++) {
        JSONObject c = topics.getJSONObject(i);

        // Storing each json item in variable
        String id = c.getString(TAG_TOPICSID);
        String topict = c.getString(TAG_TOPICTITLE);
        String username = c.getString(TAG_TOPICAUTHOR);

        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();

        // adding each child node to HashMap key => value
        map.put(TAG_TOPICSID, id);
        map.put(TAG_TOPICTITLE, topict);
        map.put(TAG_TOPICAUTHOR, username);

        // adding HashList to ArrayList
        TopicsList.add(map);
        }
    } else {
        // no products found
        // Launch Add New product Activity
       /* Intent i = new Intent(getApplicationContext(),
            NewProductActivity.class);
        // Closing all previous activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);*/
    }
    } catch (JSONException e) {
    e.printStackTrace();
    }

    return null;
}

/**
 * After completing background task Dismiss the progress dialog
 * **/
protected void onPostExecute(String file_url) {
    // dismiss the dialog after getting all products
    pDialog.dismiss();
    // updating UI from Background Thread
    runOnUiThread(new Runnable() {
    public void run() {
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
           Topics_list.this, TopicsList,
            R.layout.list_item, new String[] { TAG_TOPICSID,TAG_TOPICTITLE,
                TAG_TOPICAUTHOR},
            new int[] { R.id.tid, R.id.title });
        // updating listview
        setListAdapter(adapter);
    }
    });

}

}
 }

最新的 .php 代码版本

<?php

/*
 * Following code will list all the products
 */

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

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

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

// get all products from products table

if(array_key_exists('parent', $_GET)){
      $id = intval($_GET['parent']);
 } else {
 exit();}
 //echo json_encode ("wrong");
      // something to stop this processing
     // $response["success"]=0;
     //$response["message"] = "No";
 //echo json_encode((object)$response);}

$result = mysql_query("select  t.id, t.title, u.username,  from topics as t  left join user as u where t.parent= '$id' and t.id2=1 group by t.id order by t.timestamp2 desc")
or die(mysql_error());


// check for empty result

//if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
   // $response["topics"] = array();
    //echo json_encode((object)$response);

   // while ($row = mysql_fetch_array($result)) {
    // temp user array
    //    $topic = array();
    //    $topic["tid"] = $row["t.id"];
     //   $topic["name"] = $row["t.title"];
      //  $topic["author"] = $row["u.username"];


    // push single product into final response array

      /  array_push($response["topics"], $topic);

//}
if (mysqli_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response['topics'] = array();
    while (true) {
       $row = mysqli_fetch_array($result);
       if(!$row)break;
       // temp user array
       $topic = array();
       $topic["tid"] = $row["t.id"];
       $topic["name"] = $row["t.title"];
       $topic["author"] = $row["u.username"];
       // push single product into final response array
       array_push($response["topics"], (object)$topic);
    }

    // success
    $response["success"] = 1;

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

    // echo no users JSON
    //echo json_encode($response);
    echo json_encode((object)$response);
}
?>

我希望有人能帮助我。感谢你的帮助。对我有耐心,我不是很好。

4

1 回答 1

2

好吧,我认为您正在构建一个 mulformed json 响应。

此外,不推荐使用 Mysql,请使用 mysqli 接口。

不要单独回显每个数据库记录。

您还试图将 key => value 关联数组传递到一个普通的 json 数组中,这会导致打嗝,当您这样做时,请使用以下转换:

json_encode((object)$keyValueArray);

因为 Json 没有键值对数组,但它有对象。

这是更正和重新格式化的代码。

我的评论以 // * * * 开头

<?php

/*
 * Following code will list all the products
 */

// *** this will be the database connection 
$db = null; 

// *** We will first check for the $_GET, since if it fails, no need to 
// *** use resources, open databases etc...

// *** I have to warn you about $_GET, anything which is not numeric will
// *** give an $id of 0 so I added a numeric check..
if( (isset($_GET['parent'])) && (is_numeric($_GET['parent'])) ){
     $id = intval($_GET['parent']);
} else {
// *** Examine the function responseFailure I appended to source
// *** Inform about bad id and exit.
     responseFailure("Bad id");
}

// *** Your DB_Connect.php uses mysql commands which are deprecated
// *** So I cancelled it and put an alternative 

// include db connect class
// require_once __DIR__ . 'DB_Connect.php';
// connecting to db
// $db = new DB_CONNECT();

// *** To use mysqli interface please use the code below.  
// *** Replace the values of $dbHost, $dbUser, $dbPass & $dbName
// *** With your own connection information

$dbHost = 'Your Database Server Name';    
$dbUser = 'Your Username On That Server';
$dbPass = 'Your Password On That Server';
$dbName = 'Your Database Name On That Server';

// *** Now lets try to connect
$db = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
//  *** inform if connect fails and exit.
if(!$db)responseFailure("Unable to connect database server");

// get all products from products table 

// *** your query is complex, so build it into a string for clarity.
// *** one bug in your code was "..."'.$id.'"...' which will give a parse error

$query = "select t.id, t.title, u.username as author, " 
        ."from topics as t left join user as u where t.parent='"
        .$id
        ."' and t.id2=1 group by t.id order by t.timestamp2 desc";

$result = mysqli_query($db, $query);
//  *** inform if query fails and exit.
if(!$result)responseFailure("Database Query failed");

// check for empty result
// *** Now if no rows, leave, no need too much code depth
if(mysqli_num_rows($result) == 0) responseFailure("No topics found");

// array for JSON response
// *** We guaranteed the success now :)
$response = array('topics' => array(), 'success'=> 1);
// *** here for programming clarity I modified
// *** while ($row = mysqli_fetch_assoc($result)) {
// *** which is generally considered as a bad practice.
while (true) {
    $row = mysqli_fetch_assoc($result);
    if(!$row)break;
    // temp user array
    $topic = array();
    $topic["tid"] = $row["t.id"];
    $topic["name"] = $row["t.title"];
    $topic["author"] = $row["u.username"];
    // push single product into final response array
    // *** Yes we will echo it later
    // *** And since it is a key => value associated array
    // *** We will cast it into object while adding
    array_push($response["topics"], (object)$topic);
} // *** end while
// *** Since it is a key => value associated array
// *** We will cast it into object while encoding
echo json_encode((object)$response); // *** you can echo it now.
if($db)mysqli_close($db);            // *** close database connection
exit(0);                             // *** Job done say goodbye

// *** we may fail in multiple points
// *** so writing this as a seperate function is optimal
// *** This function exits the php script, it does not return back

function responseFailure($msg) {
    $r = array("success" => 0, "message" => $msg); // *** build response
    echo json_encode((object)$r);  // *** build json and send it
    if($db)mysqli_close($db);      // *** close database connection if open
    exit();                        // *** stop processing
}
?>

我希望这些有帮助。

于 2013-03-18T09:27:31.913 回答