我尝试使用 AsyncHttpClient API 从 php 访问数据数组。每当我尝试获取数据时,我都会异常:
org.json.JSONException: Value 0 at success of type java.lang.String cannot be converted to JSONArray
我不确定这里出了什么问题。
如果 $response["success"] = 1 那么我想做一些事情,如果不是,我想为我试图访问成功值的值 toast 。
这是我的 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 对象添加字段更好。
关于java - org.json.JSONException : Value 0 at success of type java. lang.String 无法转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26669649/