我的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");
当我运行我的安卓应用程序时,我似乎不断收到错误:
"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);
演示;http://codepad.viper-7.com/RPtchU
JSonobject,而是使用 JSONArray
JSONArray array = new JSONArray(sourceString);
稍后遍历数组并执行业务逻辑。
http://www.json.org/javadoc/org/json/JSONArray.html
也许有这种 json 结构?
$status[$rows['Aircraft']]= $rows['Status'];
你得到一个JSONArray,不是对象,你可以创建一个包含数组或解析数组的对象。参考这篇文章
Solution #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");
}
然后你可以像这样使用它:
JSONArray jsonArray = new JSONArray(result); // note the *JSONArray* vs your *JSONObject*
n870 = getProp("A70_870", jsonArray);
n871 = getProp("A70_871", jsonArray);
...
注意 我还没有测试过这段代码,所以你可能需要做一些改变...
替代解决方案 (PHP(
自从我使用 PHP 以来已经有一段时间了,但是您也许可以保持 Java 代码不变,并将 PHP int 的 while
循环正文更改为:
$status[$rows['Aircraft']] = $rows['Status'];