我的 PHP 代码是这样的:
$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status");
#$row = mysql_fetch_row($userdetails) ;
while($rows=mysqli_fetch_array($userdetails)){
$status[]= array($rows['Aircraft']=>$rows['Status']);
}
#Output the JSON data
echo json_encode($status);
并给出这个:
[{"A70_870":"1"},{"A70_871":"1"},{"A70_872":"1"},{"A70_873":"1"},{"A70_874":"1"},{"A70_875":"1"},{"A70_876":"2"},{"A70_877":"1"},{"A70_878":"2"},{"A70_879":"2"},{"A70_880":"2"},{"A70_881":"0"},{"A70_882":"0"},{"A70_883":"0"},{"A70_884":"0"},{"A70_885":"0"}]
读取它的java代码是这样的:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
n870 = jsonObject.getInt("A70_870");
n871 = jsonObject.getInt("A70_871");
n872 = jsonObject.getInt("A70_872");
n873 = jsonObject.getInt("A70_873");
n874 = jsonObject.getInt("A70_874");
n875 = jsonObject.getInt("A70_875");
n876 = jsonObject.getInt("A70_876");
n877 = jsonObject.getInt("A70_877");
n878 = jsonObject.getInt("A70_878");
n879 = jsonObject.getInt("A70_879");
n880 = jsonObject.getInt("A70_880");
n881 = jsonObject.getInt("A70_881");
n882 = jsonObject.getInt("A70_882");
n883 = jsonObject.getInt("A70_883");
n884 = jsonObject.getInt("A70_884");
n885 = jsonObject.getInt("A70_885");
当我运行我的 android 应用程序时,我似乎不断收到错误消息:
"of type org.json.JSONArray cannot be converted into Json object"
但是,当我发送不带方括号的应用虚拟代码时,它似乎工作正常!我如何摆脱末端的那些 [ 和 ] 括号???
或者有没有办法按原样接受 json 并调整 java 来读取它?
最佳答案
echo json_encode($status, JSON_FORCE_OBJECT);
演示:http://codepad.viper-7.com/lrYKv6
或
echo json_encode((Object) $status);
关于java - 从 Android Java 代码的 php Json 结果中删除结尾 [ 和 ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19306342/