因此,當我嘗試解析JSON對象時,出現該錯誤。我有谷歌的問題,我仍然困惑,無法找到解決辦法。它看起來像我的代碼是正確的。JSONException:解析時無法將類型java.lang.String的值轉換爲JSONObject
這是Android的Java文件
InputStream is = null;
String result = "";
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.v("mysql", "Success");
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return null;
}
protected void onPostExecute(String result) {
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.v("result", result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","uID: "+json_data.getInt("uID")+
", uName: "+json_data.getString("uName")+
", uPass: "+json_data.getString("uPass")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
的PHP文件中的代碼是這樣
<?php
$username = "removed";
$password = "removed";
$database = "removed";
$user = "art";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die ("it's dead jim");
$q = mysql_query("SELECT * FROM user WHERE uName = '$user'");
while($e=mysql_fetch_assoc($q)){
print(json_encode($e));
$output[]=$e;
}
?>
的JSON值我收到是
{ 「UID」:「1 「,」uName「:」藝術「,」uPass「:」密碼「}
當我嘗試分析它,我得到:
錯誤的數據進行解析org.json.JSONException:值 { 「UID」: 「1」, 「UNAME」: 「藝術」, 「uPass」:」類型的密碼「} org.json.JSONObject 不能轉換爲JSONArray
您對異常消息有什麼不瞭解?你知道JSON格式嗎? –
我瞭解它無法轉換的錯誤,但我不完全明白我在做什麼錯誤以及如何解決它。我知道我將它存儲到一個JSONArray中,但是我還可以存儲它來解析它嗎? – user2574427
當您嘗試將它解析爲JSONArray時,它是JSONObject。 –