解析数据时出错 org.json.JSONException: Value <br><table of type java.lang.String cannot be convert to JSONObject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22917217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
提问by Luciano Santis
I'm trying to display information depending on the item pressed in a ListView. I'm using a HTTP GET request to get the information.
我试图根据在 ListView 中按下的项目来显示信息。我正在使用 HTTP GET 请求来获取信息。
When you click on an item (profile) in the ListView the application gets that profile name and depending on that it should display that profile's information in the next activity but that's not working and I keep getting a JSONException
error. I don't know what is causing or if my approach to achieve this is wrong, any help would be great. Thanks.
当您单击 ListView 中的一个项目(配置文件)时,应用程序会获取该配置文件名称,并根据它应该在下一个活动中显示该配置文件的信息,但这不起作用,我不断收到JSONException
错误消息。我不知道是什么原因造成的,或者如果我实现这一目标的方法是错误的,任何帮助都会很棒。谢谢。
Here I'm sending the profile's name to the next activity (This class has more code but it's not relevant for this question):
在这里,我将配置文件的名称发送到下一个活动(该类有更多代码,但与此问题无关):
public class EditProfiles extends BaseListActivity implements GetProfilesListener{
公共类 EditProfiles 扩展 BaseListActivity 实现 GetProfilesListener{
TextView errorMessage;
String email;
private static final String TAG_PNAME = "profilename";
/**
* Called when activity is first created.
*/
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profiles);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String profilename = ((TextView) view.findViewById(R.id.editProfiles_profile_name)).getText()
.toString();
Intent in = new Intent(getApplicationContext(), EditSingleProfile.class);
// sending profilename to next activity
in.putExtra(TAG_PNAME, profilename);
// Starts activity
startActivity(in);
}
});
}
This is the activity where I want to get the details from the profile:
这是我想从个人资料中获取详细信息的活动:
public class EditSingleProfile extends BaseViewEditProfile{
Spinner inputType;
EditText inputName;
EditText inputAge;
EditText inputBreed;
EditText inputAbout;
ImageView selectPicture;
Button change;
TextView message;
//Json node names.
private static final String TAG_SUCCESS = "success";
private static final String TAG_PROFILE = "profile";
private static final String TAG_PNAME = "profilename";
private static final String TAG_PAGE = "petage";
private static final String TAG_BREED = "petbreed";
private static final String TAG_ABOUT = "profileabout";
//JSON parser class
JSONParser jsonParser = new JSONParser();
// single profile url
private static final String url_profile_details = "http://gatoandroidapp.comeze.com/profile_details.php";
//Create field SELECT_PICTURE to be used in the class.
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
String pimage;
String profilename;
/**
* Called when activity is created.
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile_view);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// getting profile details from intent
Intent i = getIntent();
// getting profile name from intent
profilename = i.getStringExtra(TAG_PNAME);
// Sets view title.
this.setTitle(profilename);
// Get profile's details in Background Thread
new GetProfiles().execute();
/**
* Background AsyncTask to Get profile details.
*/
class GetProfiles extends AsyncTask<String, String, String> {
// Progress Dialog
private ProgressDialog pDialog;
/**
* Before starting background thread Show Progress Dialog
*/
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditSingleProfile.this);
pDialog.setMessage("Loading profile details...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting profile details in background thread
*/
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("profilename", profilename));
// getting profile details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_profile_details, "GET", params);
// check your log for json response
Log.d("Single Profile Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray profileObj = json
.getJSONArray(TAG_PROFILE); // JSON Array
// get first profile object from JSON Array
JSONObject profile = profileObj.getJSONObject(0);
inputName = (EditText) findViewById(R.id.editProfile_profileName_editText);
inputAge = (EditText) findViewById(R.id.editProfile_age_editText);
inputBreed = (EditText) findViewById(R.id.editProfile_breed_editText);
inputAbout = (EditText) findViewById(R.id.editProfile_about_editText);
// display product data in EditText
inputName.setText(profile.getString(TAG_PNAME));
inputAge.setText(profile.getString(TAG_PAGE));
inputBreed.setText(profile.getString(TAG_BREED));
inputAbout.setText(profile.getString(TAG_ABOUT));
}else{
// profile with name not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog.
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
This is my JSON parser:
这是我的 JSON 解析器:
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 mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equalsIgnoreCase("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.equalsIgnoreCase("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;
}
}
This is my PHP code:
这是我的 PHP 代码:
<?php
/*
* Gets single profile details
* A profile is identified by profile name (pname)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/DB_Connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["profilename"])) {
$profilename = $_GET['profilename'];
// get a profile from profiles table
$result = mysql_query("SELECT * FROM profiles WHERE profilename = $profilename");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$profile = array();
$profile["profilename"] = $result["profilename"];
$profile["petage"] = $result["petage"];
$profile["petbreed"] = $result["petbreed"];
$profile["profileabout"] = $result["profileabout"];
// success
$response["success"] = 1;
// user node
$response["profile"] = array();
array_push($response["profile"], $profile);
// echoing JSON response
echo json_encode($response);
} else {
// no profile found
$response["success"] = 0;
$response["message"] = "No profile found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no profile found
$response["success"] = 0;
$response["message"] = "No profile 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);
}
?>
This is the error log:
这是错误日志:
04-07 16:22:00.156: E/JSON Parser(15588): Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
04-07 16:22:00.156: D/AndroidRuntime(15588): Shutting down VM
04-07 16:22:00.156: W/dalvikvm(15588): threadid=1: thread exiting with uncaught exception (group=0x4123f908)
04-07 16:22:00.159: E/AndroidRuntime(15588): FATAL EXCEPTION: main
04-07 16:22:00.159: E/AndroidRuntime(15588): java.lang.NullPointerException
04-07 16:22:00.159: E/AndroidRuntime(15588): at com.gmail.lucsantisf.software_project.views.EditSingleProfile$GetProfiles.run(EditSingleProfile.java:249)
04-07 16:22:00.159: E/AndroidRuntime(15588): at android.os.Handler.handleCallback(Handler.java:615)
04-07 16:22:00.159: E/AndroidRuntime(15588): at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 16:22:00.159: E/AndroidRuntime(15588): at android.os.Looper.loop(Looper.java:153)
04-07 16:22:00.159: E/AndroidRuntime(15588): at android.app.ActivityThread.main(ActivityThread.java:5006)
04-07 16:22:00.159: E/AndroidRuntime(15588): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 16:22:00.159: E/AndroidRuntime(15588): at java.lang.reflect.Method.invoke(Method.java:511)
04-07 16:22:00.159: E/AndroidRuntime(15588): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
04-07 16:22:00.159: E/AndroidRuntime(15588): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
04-07 16:22:00.159: E/AndroidRuntime(15588): at dalvik.system.NativeStart.main(Native Method)
Thanks for any help.
谢谢你的帮助。
采纳答案by Luciano Santis
Well I fixed the error, the problem had to do with the connection in the PHP file and this line : require_once DIR. '/DB_Connect.php';.
好吧,我修复了错误,问题与 PHP 文件中的连接和这一行有关: require_once DIR。'/DB_Connect.php';。
I used Log.d("JSON Parser", json ); to read the PHP error in logcat in eclipse and it kept telling me that failed to open stream: no such file or directory and fail opening requires so I put the file required in the same directory as my php file and in the php file and I replaced this line: require_once _DIR_ . '/DB_Connect.php';with this: require_once'DB_Connect.php';
我使用了 Log.d("JSON Parser", json ); 在 Eclipse 中读取 logcat 中的 PHP 错误,它一直告诉我无法打开流:没有这样的文件或目录并且无法打开需要,所以我将所需的文件与我的 php 文件和 php 文件放在同一目录中,然后我替换了这一行:require_once _ DIR_ 。'/DB_Connect.php'; 用这个:require_once 'DB_Connect.php';
The java code is perfect in case that someone is trying to do something similar.
如果有人试图做类似的事情,java 代码是完美的。
回答by hyarion
It looks like the response you are getting is not valid JSON. The Value <br><table of type java.lang.String
indicates you are getting HTML code as the response which it cannot map to your objects.
您收到的响应似乎不是有效的 JSON。在Value <br><table of type java.lang.String
表示你正在HTML代码,它不能映射到你的对象的响应。
Try doing a
尝试做一个
Log.d("JSON Parser", json);
Just before your comment // try parse the string to a JSON object
就在你发表评论之前 // try parse the string to a JSON object
回答by alvaropgl
With Logcat output the url you are requesting and try to visualize the response, and pay attention to the symbols and tags like < />, they should be escaped. May be the parser has encounter an array and you are telling to convert to an object.
使用 Logcat 输出您请求的 url 并尝试可视化响应,并注意像 < /> 这样的符号和标签,它们应该被转义。可能是解析器遇到了一个数组,而您正在告诉要转换为一个对象。
回答by Iratzar Carrasson Bores
this error can be because when you execute PHP code appear this error:
这个错误可能是因为当你执行 PHP 代码时出现这个错误:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in
And it gets this error through JSON:
它通过 JSON 得到这个错误:
<br>Deprecated</br>...
So, if you put in your php code something like this:
所以,如果你输入你的 php 代码是这样的:
error_reporting(E_ALL ^ E_DEPRECATED);
This error will be fixed.
此错误将被修复。