【问题标题】:JSON array and Android list view not workingJSON数组和Android列表视图不起作用
【发布时间】:2012-02-14 18:49:39
【问题描述】:

好的,我有一个 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。我试图修改代码以获取和排列但我没有运气,有人可以帮忙吗?安卓系统是:http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/

我遇到问题的主要部分是这行代码:

    JSONArray  earthquakes = json.getJSONArray("earthquakes");

显然我的 JSON 没有像示例那样的元素标识符,当我删除该行时它不起作用。任何帮助都会很棒,谢谢!

【问题讨论】:

    标签: php android json arrays


    【解决方案1】:

    虽然您的 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 服务中很常见。

    更新 根据this,外部必须是一个对象。在我的回答中使用推荐的结构,您的行将是:

    JSONArray  teams = json.getJSONArray("teams");
    

    【讨论】:

      【解决方案2】:

      只需通过添加一个顶级来修改您的输出:

      print(json_encode(array('earthquakes' => $output)));
      

      【讨论】:

        猜你喜欢
        • 2013-10-09
        • 2015-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        相关资源
        最近更新 更多