JSON error: java.lang.String cannot be converted to JSONObject
JSON error: java.lang.String cannot be converted to JSONObject
我正在开发一个 android 应用程序,我正在尝试使用 Volley 库。我无法解决的问题是关于 JSON。我检查了我的 php 文件、结果和 Java 代码,但我仍然遇到同样的错误。
有趣的是 VolleyLog 没有显示错误消息,但是 Log,确实如此。
E/Volley﹕ [1] 2.onErrorResponse: VOLLEY_ERROR
和
E/LOG﹕ Error: org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONObject
那是我的 PHP 代码:
<?php
# Inform which carachters type will be used.
header('Content-Type: text/html; charset=utf-8');
// array for JSON response
$response = array();
// include db connect class
require_once ('../conn.php');
require_once('pClass.php');
error_reporting( E_ALL );
// connecting to db
$db = new DB_CONNECT();
//Setting to UTF8
mysql_query("SET NAMES 'utf8_general_ci'");
mysql_query('SET character_set_connection=utf8_general_ci');
mysql_query('SET character_set_client=utf8_general_ci');
mysql_query('SET character_set_results=utf8_general_ci');
mysql_query('SET CHARACTER SET utf8');
$ff_error = "ERROR";
$arrPOI["arrPOI"] = array();
$poi=new POI();
if (isset($_REQUEST["ff_01"]))
{
//Execute the query
$ff_01 = $_REQUEST['ff_01'];
$return = mysql_query($ff_01) or die(mysql_error());
// check for empty result
if (mysql_num_rows($return) > 0) {
while ($row = mysql_fetch_array($return)) {
$poi->setPOIId($row["intPointId"]);
$poi->setPOIName($row["vchPointName"]);
$poi->setPOIImage($row["vchAwesomeFont"]);
$poi->setStatusId($row["intStatusId"]);
$poi->setLanguageId($row["intLanguageId"]);
// push single category into final response array
array_push($arrPOI["arrPOI"], $poi->getPOIData());
}
// echoing JSON response
header('Content-Type: application/json');
echo json_encode($arrPOI, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK | JSON_NUMERIC_CHECK);
} else {
//No data found
array_push($arrPOI["arrPOI"], $poi->getPOIData());
// echo no users JSON
header('Content-Type: application/json');
echo json_encode($arrPOI);
}
} else {
//ERROR
array_push($arrPOI["arrPOI"], $poi->getPOIData());
//Echo
header('Content-Type: application/json');
echo json_encode($arrPOI);
}
?>
PHP 结果:
{"arrPOI":[{"intPOIId":1,"strPOIName":"Cinema","strPOIImage":"fa-film","intStatusId":1,"intLanguageId":1},{"intPOIId":2,"strPOIName":"Teatro","strPOIImage":"fa-smile-o|fa-frown-o","intStatusId":1,"intLanguageId":1},{"intPOIId":3,"strPOIName":"Restaurante","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":4,"strPOIName":"Bar","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":5,"strPOIName":"Pontos TurÃsticos","strPOIImage":"fa-map-marker","intStatusId":1,"intLanguageId":1},{"intPOIId":6,"strPOIName":"Cafeteria","strPOIImage":"fa-coffee","intStatusId":1,"intLanguageId":1},{"intPOIId":7,"strPOIName":"Shopping","strPOIImage":"fa-diamond","intStatusId":1,"intLanguageId":1},{"intPOIId":8,"strPOIName":"Livraria","strPOIImage":"fa-book","intStatusId":1,"intLanguageId":1},{"intPOIId":9,"strPOIName":"Show","strPOIImage":"fa-microphone","intStatusId":1,"intLanguageId":1},{"intPOIId":10,"strPOIName":"Boates","strPOIImage":"fa-glass","intStatusId":1,"intLanguageId":1},{"intPOIId":11,"strPOIName":"Lanchonete","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":12,"strPOIName":"Hotéis","strPOIImage":"fa-building","intStatusId":1,"intLanguageId":1},{"intPOIId":13,"strPOIName":"Pub","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":14,"strPOIName":"Pizzaria","strPOIImage":"fa-pie-chart","intStatusId":1,"intLanguageId":1},{"intPOIId":15,"strPOIName":"Univesidade","strPOIImage":"fa-university","intStatusId":1,"intLanguageId":1},{"intPOIId":16,"strPOIName":"Hospital","strPOIImage":"fa-plus-square","intStatusId":1,"intLanguageId":1}]}
还有我的Java代码:
import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.game.code.guide44.adapter.POIAdapter;
import com.game.code.guide44.app.AppController;
import com.game.code.guide44.data.PointOfInterest;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class POIChoose extends Activity {
private ListView lVwPOI;
private POIAdapter adapterPOI;
private ProgressDialog pDialog;
private List<PointOfInterest> POIList;
private String url;
private StringBuilder stbCheckedPOI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poi_choose);
//Initialize with ListView object from activity_poi_choose by id
lVwPOI = (ListView)findViewById(R.id.lvwPOI);
//Initialize the list of POI
POIList = new ArrayList<PointOfInterest>();
//initialize with POI List
adapterPOI = new POIAdapter(this, POIList);
//Fill the LiistView with POIAdapter content
lVwPOI.setAdapter(adapterPOI);
stbCheckedPOI = new StringBuilder();
//Base url
//Change "1" to dynamic user language
url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1");
//Initialize the ProgressDialog
pDialog = new ProgressDialog(POIChoose.this);
//Show the progress bar befores making HTTP request
pDialog.setMessage(getString(R.string.txtMsgPleaseWait));
pDialog.show();
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
VolleyLog.v("VOLLEY", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(error instanceof NoConnectionError)
Toast.makeText(POIChoose.this, "No internet available", Toast.LENGTH_SHORT).show();
else if(error instanceof ServerError)
Toast.makeText(POIChoose.this, "Server Error", Toast.LENGTH_SHORT).show();
VolleyLog.e("VOLLEY_ERROR", "Error: " + error.getMessage());
Log.e("LOG", "Error: " + error.getMessage());
pDialog.dismiss();
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private void parseJsonFeed(JSONObject response){
try{
JSONArray jsonArray = response.getJSONArray("arrPOI");
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
PointOfInterest Poi = new PointOfInterest();
Poi.setPOIId(jsonObject.getInt("intPointId"));
Poi.setPOIName(jsonObject.getString("vchPointName"));
Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));
// adding movie to movies array
POIList.add(Poi);
}
} catch(JSONException e){
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_first_choose, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void performSelectPOI(View view){
for(int i = 0; i < POIList.size(); i++)
{
if(adapterPOI.mCheckStates.get(i)==true)
{
stbCheckedPOI.append(POIList.get(i).toString());
stbCheckedPOI.append("\n");
}
else
{
}
}
Toast.makeText(AppController.getContext(), stbCheckedPOI, Toast.LENGTH_LONG).show();
}
}
我也听说过 GSON。这是解决方案吗?谁能帮我?提前致谢!!
好吧,我的朋友们,我尝试了所有方法来解决 Java 代码中的问题,但我差点忘了看看我的 PHP 收到了什么。
在我的这部分代码中:
url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1");
我将 SQL 查询作为参数传递。好吧,PHP 没有收到所有查询。例如:如果我通过
"SELECT ID, NAME, ORDER FROM tblOrder"
my PHP 仅接收 "SELECT",生成错误(很明显!!)。所以问题不是 BOM 或 UTF-8 或类似的东西......是一个基本错误。
因此,解决方案是将 SQL 查询放在 PHP 中,并仅传递几个参数以接收正确答案(在本例中为 JSONObject)
非常感谢!!
P.S.: 感谢 Xjasz!你是对的!!我需要改变这个:
Poi.setPOIId(jsonObject.getInt("intPointId"));
Poi.setPOIName(jsonObject.getString("vchPointName"));
Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));
为此:
Poi.setPOIId(jsonObject.getInt("intPOIId"));
Poi.setPOIName(jsonObject.getString("strPOIName"));
Poi.setPOIPicture(jsonObject.getString("strPOIImage"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));
谢谢大佬!!
我正在开发一个 android 应用程序,我正在尝试使用 Volley 库。我无法解决的问题是关于 JSON。我检查了我的 php 文件、结果和 Java 代码,但我仍然遇到同样的错误。
有趣的是 VolleyLog 没有显示错误消息,但是 Log,确实如此。
E/Volley﹕ [1] 2.onErrorResponse: VOLLEY_ERROR
和
E/LOG﹕ Error: org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONObject
那是我的 PHP 代码:
<?php
# Inform which carachters type will be used.
header('Content-Type: text/html; charset=utf-8');
// array for JSON response
$response = array();
// include db connect class
require_once ('../conn.php');
require_once('pClass.php');
error_reporting( E_ALL );
// connecting to db
$db = new DB_CONNECT();
//Setting to UTF8
mysql_query("SET NAMES 'utf8_general_ci'");
mysql_query('SET character_set_connection=utf8_general_ci');
mysql_query('SET character_set_client=utf8_general_ci');
mysql_query('SET character_set_results=utf8_general_ci');
mysql_query('SET CHARACTER SET utf8');
$ff_error = "ERROR";
$arrPOI["arrPOI"] = array();
$poi=new POI();
if (isset($_REQUEST["ff_01"]))
{
//Execute the query
$ff_01 = $_REQUEST['ff_01'];
$return = mysql_query($ff_01) or die(mysql_error());
// check for empty result
if (mysql_num_rows($return) > 0) {
while ($row = mysql_fetch_array($return)) {
$poi->setPOIId($row["intPointId"]);
$poi->setPOIName($row["vchPointName"]);
$poi->setPOIImage($row["vchAwesomeFont"]);
$poi->setStatusId($row["intStatusId"]);
$poi->setLanguageId($row["intLanguageId"]);
// push single category into final response array
array_push($arrPOI["arrPOI"], $poi->getPOIData());
}
// echoing JSON response
header('Content-Type: application/json');
echo json_encode($arrPOI, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK | JSON_NUMERIC_CHECK);
} else {
//No data found
array_push($arrPOI["arrPOI"], $poi->getPOIData());
// echo no users JSON
header('Content-Type: application/json');
echo json_encode($arrPOI);
}
} else {
//ERROR
array_push($arrPOI["arrPOI"], $poi->getPOIData());
//Echo
header('Content-Type: application/json');
echo json_encode($arrPOI);
}
?>
PHP 结果:
{"arrPOI":[{"intPOIId":1,"strPOIName":"Cinema","strPOIImage":"fa-film","intStatusId":1,"intLanguageId":1},{"intPOIId":2,"strPOIName":"Teatro","strPOIImage":"fa-smile-o|fa-frown-o","intStatusId":1,"intLanguageId":1},{"intPOIId":3,"strPOIName":"Restaurante","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":4,"strPOIName":"Bar","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":5,"strPOIName":"Pontos TurÃsticos","strPOIImage":"fa-map-marker","intStatusId":1,"intLanguageId":1},{"intPOIId":6,"strPOIName":"Cafeteria","strPOIImage":"fa-coffee","intStatusId":1,"intLanguageId":1},{"intPOIId":7,"strPOIName":"Shopping","strPOIImage":"fa-diamond","intStatusId":1,"intLanguageId":1},{"intPOIId":8,"strPOIName":"Livraria","strPOIImage":"fa-book","intStatusId":1,"intLanguageId":1},{"intPOIId":9,"strPOIName":"Show","strPOIImage":"fa-microphone","intStatusId":1,"intLanguageId":1},{"intPOIId":10,"strPOIName":"Boates","strPOIImage":"fa-glass","intStatusId":1,"intLanguageId":1},{"intPOIId":11,"strPOIName":"Lanchonete","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":12,"strPOIName":"Hotéis","strPOIImage":"fa-building","intStatusId":1,"intLanguageId":1},{"intPOIId":13,"strPOIName":"Pub","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":14,"strPOIName":"Pizzaria","strPOIImage":"fa-pie-chart","intStatusId":1,"intLanguageId":1},{"intPOIId":15,"strPOIName":"Univesidade","strPOIImage":"fa-university","intStatusId":1,"intLanguageId":1},{"intPOIId":16,"strPOIName":"Hospital","strPOIImage":"fa-plus-square","intStatusId":1,"intLanguageId":1}]}
还有我的Java代码:
import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.game.code.guide44.adapter.POIAdapter;
import com.game.code.guide44.app.AppController;
import com.game.code.guide44.data.PointOfInterest;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class POIChoose extends Activity {
private ListView lVwPOI;
private POIAdapter adapterPOI;
private ProgressDialog pDialog;
private List<PointOfInterest> POIList;
private String url;
private StringBuilder stbCheckedPOI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poi_choose);
//Initialize with ListView object from activity_poi_choose by id
lVwPOI = (ListView)findViewById(R.id.lvwPOI);
//Initialize the list of POI
POIList = new ArrayList<PointOfInterest>();
//initialize with POI List
adapterPOI = new POIAdapter(this, POIList);
//Fill the LiistView with POIAdapter content
lVwPOI.setAdapter(adapterPOI);
stbCheckedPOI = new StringBuilder();
//Base url
//Change "1" to dynamic user language
url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1");
//Initialize the ProgressDialog
pDialog = new ProgressDialog(POIChoose.this);
//Show the progress bar befores making HTTP request
pDialog.setMessage(getString(R.string.txtMsgPleaseWait));
pDialog.show();
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
VolleyLog.v("VOLLEY", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(error instanceof NoConnectionError)
Toast.makeText(POIChoose.this, "No internet available", Toast.LENGTH_SHORT).show();
else if(error instanceof ServerError)
Toast.makeText(POIChoose.this, "Server Error", Toast.LENGTH_SHORT).show();
VolleyLog.e("VOLLEY_ERROR", "Error: " + error.getMessage());
Log.e("LOG", "Error: " + error.getMessage());
pDialog.dismiss();
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private void parseJsonFeed(JSONObject response){
try{
JSONArray jsonArray = response.getJSONArray("arrPOI");
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
PointOfInterest Poi = new PointOfInterest();
Poi.setPOIId(jsonObject.getInt("intPointId"));
Poi.setPOIName(jsonObject.getString("vchPointName"));
Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));
// adding movie to movies array
POIList.add(Poi);
}
} catch(JSONException e){
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_first_choose, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void performSelectPOI(View view){
for(int i = 0; i < POIList.size(); i++)
{
if(adapterPOI.mCheckStates.get(i)==true)
{
stbCheckedPOI.append(POIList.get(i).toString());
stbCheckedPOI.append("\n");
}
else
{
}
}
Toast.makeText(AppController.getContext(), stbCheckedPOI, Toast.LENGTH_LONG).show();
}
}
我也听说过 GSON。这是解决方案吗?谁能帮我?提前致谢!!
好吧,我的朋友们,我尝试了所有方法来解决 Java 代码中的问题,但我差点忘了看看我的 PHP 收到了什么。
在我的这部分代码中:
url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1");
我将 SQL 查询作为参数传递。好吧,PHP 没有收到所有查询。例如:如果我通过
"SELECT ID, NAME, ORDER FROM tblOrder"
my PHP 仅接收 "SELECT",生成错误(很明显!!)。所以问题不是 BOM 或 UTF-8 或类似的东西......是一个基本错误。
因此,解决方案是将 SQL 查询放在 PHP 中,并仅传递几个参数以接收正确答案(在本例中为 JSONObject)
非常感谢!!
P.S.: 感谢 Xjasz!你是对的!!我需要改变这个:
Poi.setPOIId(jsonObject.getInt("intPointId"));
Poi.setPOIName(jsonObject.getString("vchPointName"));
Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));
为此:
Poi.setPOIId(jsonObject.getInt("intPOIId"));
Poi.setPOIName(jsonObject.getString("strPOIName"));
Poi.setPOIPicture(jsonObject.getString("strPOIImage"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));
谢谢大佬!!