0

我有以下 php 文件....

    mysql_connect("localhost","root","");
    mysql_select_db("database_name");
    $sql=mysql_query("select * from members");
    while($row=mysql_fetch_assoc($sql)) $output[]=$row;
    print(json_encode($output));
    mysql_close();
     ?>

有了这个,我得到了 android 中的所有数据,下面是我的 android 内容,

        BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }

    is.close();
    String json = sb.toString();

我得到了 json 作为字符串。从 android 但现在我想在 listview 中使用该数据。我无法理解如何使用它。请给我一些想法或建议。

4

3 回答 3

2

从 Json 解析数据并将其保存在 ArrayList 中,并将该 arrayList 设置为 Listview。

您可以从 String 创建 Json 对象,如下所示。

JSONObject jsonObject = new JSONObject(json);

您可以从 String 创建 Json Array 对象,如下所示。

JSONArray ja = new JSONArray(json);

看看这个教程

于 2012-08-31T08:28:19.967 回答
1

Android中的JSON 包为您提供了所需的类。

您可以使用您的数据轻松创建 JSONObject,如下所示:

JSONObject jsonObject = new JSONObject(json);

如果你有 JSONArray,你可以对 JSONArray 类做同样的事情:

JSONArray jsonArray = new JSONArray(json);

只要它是有效的 JSON,您的 JSON 的来源就无关紧要。

您需要在 Java 中创建模型类并将解析的 JSON 数据提供给模型。然后这些可以用于在 ListView 中显示内容。

于 2012-08-31T08:30:30.290 回答
1

我强烈推荐 GSON 库将您的 json 字符串序列化为 java 对象。您可以在此处获取 GSON 包http://code.google.com/p/google-gson/

一旦你将 GSON 添加到你的 android 构建路径,剩下的就很简单了。从 json 字符串解析为 java 对象就这么简单,

gsonObject.fromJson("JSON STRING", ObjectModel.class);

有关 Gson api 的更多信息,请点击此处

https://sites.google.com/site/gson/gson-user-guide

于 2012-08-31T08:32:35.403 回答