我尝试使用AsyncHttpClient API从php访问数据数组。每当我尝试获取数据时,我都会例外:
org.json.JSONException: Value 0 at success of type java.lang.String cannot be converted to JSONArray
我不确定这里出什么问题了。
如果$ response [“ success”] = 1,那么我想做些什么,如果不想,我想举一个我要尝试获取成功值的值。
这是我的PHP文件:
<?php
include("config.php");
$response = array();
if (isset($_GET['userID']))
{
$userID = $_GET['userID'];
// mysql inserting a new row
$result = //MY QUERY GOES HERE
// check for empty result
if (mysql_num_rows($result) > 0)
{
$response["data"] = array();
while ($row = mysql_fetch_array($result))
{
// temp user array
$detail = array();
$detail["userID"] = $row["username"];
$detail["password"] = $row["password"];
array_push($response["data"], $detail);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else
{
// no products found
$response["success"] = 0;
// echo no users JSON
echo json_encode($response);
}
}
else
{
// no products found
$response["success"] = 0;
// echo no users JSON
echo json_encode($response);
}
?>
而我的Android代码:
AsyncHttpClient client = new AsyncHttpClient();
client.get(uploadWebsite, requestParams, new JsonHttpResponseHandler()
{
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
try
{
JSONArray sucessdetails = response.getJSONArray("success");
for (int i = 0; i < sucessdetails.length(); i++)
{
JSONObject successObject = sucessdetails.getJSONObject(i);
Log.e("Value","Of success"+successObject);
}
}
catch (JSONException e)
{
Log.e("ERROR","E"+e);
e.printStackTrace();
}
}
});
有人可以帮我解决这个问题吗,我过去1天一直在努力。 SO似乎有类似的问题,但没有确切的问题。
谢谢!
最佳答案
看来您是要这样做:
if (response.getInt("success") == 1) {
JSONArray sucessdetails = response.getJSONArray("data");
for (int i = 0; i < sucessdetails.length(); i++) {
JSONObject successObject = sucessdetails.getJSONObject(i);
Log.e("Value","Of success"+successObject);
}
} else {
Log.e("Status", "Failed");
}
但是,总的来说,使用HTTP状态代码指示成功与失败总比将字段添加到JSON对象更好。