好的,所以我有一个php脚本:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("FYP");
$sql=mysql_query("select team_name, games_played, games_won,
games_drawn, games_lost, goals_for, goals_against, goal_difference,
current_points from Team where team_name='Man Utd'");
while($row=mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close();
?>
它查询我的数据库,并返回所有与查询匹配的行等,然后将其编码为JSON,如下所示:
[
{
"team_name": "Man City",
"games_played": "24",
"games_won": "18",
"games_drawn": "3",
"games_lost": "3",
"goals_for": "63",
"goals_against": "19",
"goal_difference": "44",
"current_points": "57"
},
{
"team_name": "Man Utd",
"games_played": "24",
"games_won": "17",
"games_drawn": "4",
"games_lost": "3",
"goals_for": "59",
"goals_against": "24",
"goal_difference": "35",
"current_points": "55"
}
]
据我所知,它是一个JSON对象数组。然而,当我把这个数组作为列表显示在我的应用程序上时,我正在编写的教程要求它是JSONObject,而不是JSONArray。我试图修改代码以获取和数组,但我运气不佳,有人能帮忙吗?android tut是:http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
我遇到麻烦的主要部分是这行代码:
JSONArray earthquakes = json.getJSONArray("earthquakes");
很明显,我的JSON不像示例那样有元素标识符,当我删除那一行时,它就不起作用了。任何帮助都会很棒,谢谢!
虽然JSON结果字符串是合法的,但应用程序(如果按照教程建模)似乎期望一个对象作为外壳,类似于以下内容:
{ "teams":
[
{
"team_name": "Man City",
"games_played": "24",
"games_won": "18",
"games_drawn": "3",
"games_lost": "3",
"goals_for": "63",
"goals_against": "19",
"goal_difference": "44",
"current_points": "57"
},
{
"team_name": "Man Utd",
"games_played": "24",
"games_won": "17",
"games_drawn": "4",
"games_lost": "3",
"goals_for": "59",
"goals_against": "24",
"goal_difference": "35",
"current_points": "55"
}
]
}
这种格式(利用对象作为外壳)在返回JSON/JSONP的web服务中非常常见。
更新根据这一点,外部必须是一个对象。使用我的答案中推荐的结构,你的行将是:
JSONArray teams = json.getJSONArray("teams");
只需添加一个顶级即可修改输出:
print(json_encode(array('earthquakes' => $output)));