转换字符串到jsonArray失败



'我有一个PHP代码,首先计算从DB检索图像参数是否成功,然后插入响应3个参数(Id,名称,url)为每个图像。然后它返回json格式的响应。我收集响应在android的字符串的形式,然后我需要将其转换为jsonArray。当转换时,我得到异常。

PHP代码:

<?php 

//Importing dbdetails file 
require_once 'dbDetails.php';

//connection to database 
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');

//sql query to fetch all images 
$sql = "SELECT * FROM MyImages";

//getting images 
$result = mysqli_query($con,$sql);

//response array 
$response = array(); 
$response['error'] = false; 
$response['images'] = array(); 

//traversing through all the rows 
while($row = mysqli_fetch_array($result)){
$temp = array(); 
$temp['id']=$row['id'];
$temp['name']=$row['name'];
$temp['url']=$row['url'];
array_push($response['images'],$temp);
}
//displaying the response 
echo json_encode($response);
?>

result是下面代码中PHP代码的响应
android code:

@Override protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
try {
JSONArray jsonArr = new JSONArray(result);
showGrid(jsonArr);
} catch (JSONException e) {
e.printStackTrace();
txtJson.setText("Exception in jsonArry");
}
}

那么如何正确地做呢?

响应字符串是->

{"error":false,"images":[{"id":"1","name":"1","url":"https://swulj.000webhostapp.com/AndroidUploadImage/uploads/1.jpg"},{"id":"2","name":"2","url":"https://swulj.000webhostapp.com/AndroidUploadImage/uploads/2.jpg"},{"id":"3","name":"3","url":"https://swulj.000webhostapp.com/AndroidUploadImage/uploads/3.jpg"},{"id":"4","name":"ygff","url":"https://swulj.000webhostapp.com/AndroidUploadImage/uploads/4.jpg"}]}

这是正确的json格式吗?我该怎么办?

你的android代码应该是这样的

protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
try {
JSONObject jsonObj = new JSONObject(result);
showGrid(jsonObj.optJsonArray("images"));
} catch (JSONException e) {
e.printStackTrace();
txtJson.setText("Exception in jsonArry");
}
}

由于字符串响应没有被"["]",我包围了它,没有例外发生。


代码:
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
try {
String res = "[" + result + "]";
JSONArray jsonArr = new JSONArray(res);
showGrid(jsonArr);
/*JSONObject jsonObj = new JSONObject(result);
showGrid(jsonObj.optJsonArray("images"));*/
} catch (Exception e) {
e.printStackTrace();
txtJson.setText("Exception in jsonArry");
}
}

相关内容

  • 没有找到相关文章

最新更新