所以有一个PHP文件我将数组发送到我的Android设备。在我的设备收到数据后,它将其转换为字符串,然后我尝试获取使用PHP制作的assoc数组索引。以下是以前的PHP代码示例:
if(mysql_num_rows($query)){
$output = array('message' => 'Group added to your database', 'succes' => 'true');
}else{
$output = array('message' => 'Wrong username/password combination', 'succes' => 'false');
}
print(json_encode($output));
以下是我的Android项目中的代码:
protected void onPostExecute(String result) {
dialog.dismiss();
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i = 0; i < jArray.length(); i++){
json_data = jArray.getJSONObject(i);
String getMessage = json_data.getString("message");
showToast(getMessage);
}
}
catch(JSONException je){
Log.e("log_tag", "Error (JSONException): "+je.toString());
showToast(result);
}
catch (ParseException pe) {
pe.printStackTrace();
}
}
错误日志:
01-08 16:35:55.896: E/log_tag(647): Error (JSONException): org.json.JSONException: Value {"message":"Group added to your database","success":"true"} of type org.json.JSONObject cannot be converted to JSONArray
01-08 16:35:56.186: W/TextLayoutCache(647): computeValuesWithHarfbuzz -- need to force to single run
答案 0 :(得分:1)
您正尝试从表示JSONObject的字符串创建JSONArray,您应该这样做:
try{
JSONObject json_data=JSONObject(result);
String getMessage = json_data.getString("message");
showToast(getMessage);
}