[英]Error with parsing JSON object
我正在開發一個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和登錄,第二個用於主題列表
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);
}
?>
我希望有人可以幫助我。 感謝您的幫助。 對我耐心,我不是很好。
好吧,我認為你正在構建一個多樣化的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
}
?>
我希望這些有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.