【问题标题】:How to formate Json data that comes from php in android?如何在android中格式化来自php的Json数据?
【发布时间】:2012-08-31 08:26:35
【问题描述】:

我有以下 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 中使用该数据。我无法理解如何使用它。请给我一些想法或建议。

【问题讨论】:

标签: php android json


【解决方案1】:

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

您可以像下面这样从字符串创建 Json 对象。

JSONObject jsonObject = new JSONObject(json);

您可以像下面这样从字符串创建 Json Array 对象。

JSONArray ja = new JSONArray(json);

看看这个Tutorial

【讨论】:

  • 当我这样做时......................JSONObject jObj =空值; jObj = 新的 JSONObject(json);但它抛出异常:08-31 14:03:13.795: V/(657): Error:org.json.JSONException
  • @himCream 请发布您有问题的完整 logcat 错误。同时发布 json 字符串
  • 这是错误:08-31 14:09:56.693: V/(756): 错误: org.json.JSONException: Value [{"id":"5","lastname": "aaa","用户名":"aaa","名字":"aaaa","日期":"2012\/08\/30","密码":"aaaa","ip":"127.0.0.1 "},{"id":"6","lastname":"ddddd","username":"ddddd","firstname":"ddddd","date":"Jan-01-1998","密码org.json.JSONArray 类型的 ":"dddd","ip":"127.0.0.1"}] 无法转换为 JSONObject
  • @himCream 它给出了错误,因为您正在尝试将 json array 转换为 json object 。而不是 JsonObject 使用 json 数组并将您的 json 字符串传递给它。
【解决方案2】:

我强烈推荐 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

【讨论】:

    【解决方案3】:

    JSON package within Android 为您提供所需的类。

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

    JSONObject jsonObject = new JSONObject(json);
    

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

    JSONArray jsonArray = new JSONArray(json);
    

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

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

    【讨论】:

    • 当我这样做时......................JSONObject jObj =空值; jObj = 新的 JSONObject(json);但它抛出异常:08-31 14:03:13.795: V/(657): Error:org.json.JSONException –
    • 请发布您的完整 JSON 或确保其有效。
    • 我刚看到。你需要一个 JSONArray 而不是 JSONObject。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    相关资源
    最近更新 更多