【发布时间】:2021-05-01 22:31:40
【问题描述】:
我正在尝试使用 volley 从 android 中的 url 获取 json 数组,但它显示以下错误
com.android.volley.ParseError: org.json.JSONException: java.lang.String 类型的值无法转换为 JSONArray
这意味着我正在从 url 接收 html。
如何从 url 接收 json 格式的数据,以便在 android 中使用 jsonObject 或 jsonArray 进行解析
我的安卓代码是
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonArrayRequest request = new JsonArrayRequest(Method.GET, URL,null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response ) {
Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
Log.i("My success",""+response.toString());
try {
for (int i = 0; i <= response.length(); i++) {
JSONObject silver_rate_values = response.getJSONObject(i);
String Silver_Rate = silver_rate_values.getString("silver_rate");
Log.v("SilverRate", "silverRate value is" + Silver_Rate);
}
}catch (JSONException e) {
e.printStackTrace();
Log.e("Silver rate", "Json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "my error :"+error, Toast.LENGTH_LONG).show();
Log.i("My error",""+error);
}
}){
};
我的php代码是
$sql = "SELECT * FROM `user_info` \n"
. "ORDER BY `customer_info`.`updatedTime` DESC LIMIT 1";
$result = mysqli_query( $con,$sql );
if(! $result ) {
die('Could not get data: ' . mysql_error());
}
//print values to screen
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = $row['a'];
$b = $row['b'];
$c = $row['c'];
$data[] = $row;
}
header('Content-type: application/json');
$json=json_encode(array("Values" => $data));
echo $json;
?>
</body>
我的 php 输出是
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{"Values":[{"a":"8888","b":"9999","c"7777"}]} </body>
</html>
如果我从 php 代码中删除标头,则输出为 {"值":[{"a":"8888","b":"9999","c"7777"}]}
然后我也从 Android 端收到同样的错误
【问题讨论】:
-
从响应 JSON 的页面中删除所有 HTML。
-
您的 php 输出包含 html 标签。它只能包含 JSON 格式的数据。
-
@Mrudul...我也试过了..但仍然是同样的错误..
标签: php android json android-volley