我正在创建一个Android应用程序,显示存储在数据库中的每个成员的详细信息。我接收成员的详细信息为json。这是我的PHP代码,用于将数据从服务器发送到我的应用程序
<?php/*UserCake Version: 2.0.2 http://usercake.com */
require_once("models/config.php");
// json response array
$response = array("error" => FALSE);
$memberDetails = fetchAllMembers();
foreach($memberDetails as $ind=> $member){
$response["error"] = FALSE;
$response["id"] = $member["id"];
$response["member"]["name"] = $member["name"];
$response["member"]["profession"] = $member["profession"];
$response["member"]["brief_description"] = $member["brief_description"];
$response["member"]["description"] = $member["description"];
$response["member"]["filename"] = $member["filename"];
echo json_encode($response);
}
?>
这是我获取json的代码
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
//hideDialog();
try {
//JSONArray jarray=new JSONArray(response);
JSONObject jObj = new JSONObject(response);
// Log.d(TAG, "JSON Array: " + jarray.toString());
Log.d(TAG, "JSON Object: " + jObj.toString());
// boolean error = jObj.getBoolean("error");
if (jObj!=null) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("id");
JSONObject user = jObj.getJSONObject("member");
String name = user.getString("name");
String profession = user.getString("profession");
String brief_description = user.getString("brief_description");
String despriction = user.getString("description");
Toast.makeText(getApplicationContext(), "Successfully fetched members ", Toast.LENGTH_LONG).show();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
我从服务器获得响应
Register Response: {"error":false,"id":1,"member":{"name":"sidharth","profession":"singer","brief_description":"wrewt4wt4tr6e463464363","description":"ty45rt646t46436436436","filename":"upload\/Exero-Logo-top.png"}}{"error":false,"id":2,"member":{"name":"aaaaa","profession":"dwedw","brief_description":"rde3wr3w4","description":"r545w2","filename":"upload\/Exero-Logo-top.png"}}{"error":false,"id":3,"member":{"name":"fdggg","profession":"t4r54e","brief_description":"4ew5t4ew5t","description":"fdgdfg","filename":"upload\/Exero-Logo-top.png"}}
当我将该响应转换为JSONObject时,我只得到一个这样的条目
JSON Object: {"error":false,"id":1,"member":{"name":"sidharth","profession":"singer","brief_description":"wrewt4wt4tr6e463464363","description":"ty45rt646t46436436436","filename":"upload\/Exero-Logo-top.png"}}
当我尝试使用JSONArray获取所有对象时,我收到了此错误
W/System.err: org.json.JSONException: Value {"error":false,"id":1,"member":{"name":"sidharth","profession":"singer","brief_description":"wrewt4wt4tr6e463464363","description":"ty45rt646t46436436436","filename":"upload\/Exero-Logo-top.png"}} of type org.json.JSONObject cannot be converted to JSONArray
如何从响应中获取所有JSON对象