有人能告诉我我的代码中出错了什么吗?
我的PHP中有这种格式:
....//Some query from mysql table
foreach($data as $row) {
$response["error"] = FALSE;
$response["notification"]["_id"] = $row["id"];
echo json_encode($response);
}
在我的Java中,我有这个:
try {
JSONObject json = new JSONObject(response);
JSONArray jArray = json.getJSONArray("notification");
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
String iid = json_data.getString("_id");
.... //Use the requested id here
}
} catch(Exception e) {
Log.e("EE", String.valueOf(e));
}
我没有得到预期的结果。在我的日志中,它说:
EE: org.json.JSONException: Value {"_id":1} at notification of type org.json.JSONObject cannot be converted to JSONArray
我不知道出了什么问题,因为我只是一个新手。有人可以帮我吗???
答案 0 :(得分:0)
好的,所以我在这里解决了我的问题:
<强> PHP 强>
....//Some query from mysql table
$posts = array(); //Added
foreach($data as $row) {
$posts[] = array('post'=>$row); //New
}echo json_encode(array('posts'=>$posts)); //then print here
ANDROID JAVA
JSONObject json = new JSONObject(response);
JSONArray jArray = json.getJSONArray("posts");
for (int i = 0; i < jArray.length(); i++) {
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
String iid = jObject.getString("id"); //Put the id here or you can add more if you have more than 1 column
Log.w("THE REQUESTED ID ARE",iid);
.... //Use the requested id here
}
感谢您的链接:
Send and Receive JSON between Android and PHP Web Service
感谢。