从Android Java代码的php Json结果中删除end[和]
我的PHP代码如下:从Android Java代码的php Json结果中删除end[和],java,php,android,arrays,json,Java,Php,Android,Arrays,Json,我的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 e
$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);
演示:
或
演示 使用JSONArray而不是使用JSonobject
JSONArray array = new JSONArray(sourceString);
稍后循环遍历数组并执行业务逻辑
如果得到的是JSONArray,而不是Object,则可以创建一个包含数组的对象,或者解析数组。
参考post可能使用这种json结构
$status[$rows['Aircraft']]= $rows['Status'];
解决方案#1(Java)
像这样的助手方法如何:
private int getProp(String name, JSONArray arr) throws Exception {
for (int i = 0; i < arr.length(); ++i) {
JSONObject obj = arr.getJSONObject(i);
if (obj.has(name))
return obj.getInt(name);
}
throw new Exception("Key not found");
}
注意我还没有测试这段代码,所以您可能需要做一些更改
替代解决方案(PHP)
我已经有一段时间没有使用PHP了,但是您可以保持Java代码不变,并在的循环体中将PHP更改为:
$status[$rows['Aircraft']] = $rows['Status'];
删除括号将破坏json。你有一个对象数组。去掉括号“删除”数组,现在你得到了一堆逗号分隔的对象,这些对象不是有效的javascript/json。感谢所有其他人也回答了这个问题,但这很好地解决了第一步!!!!干杯,拉乔斯!你就是那个人。
JSONArray jsonArray = new JSONArray(result); // note the *JSONArray* vs your *JSONObject*
n870 = getProp("A70_870", jsonArray);
n871 = getProp("A70_871", jsonArray);
...
$status[$rows['Aircraft']] = $rows['Status'];