java - 如何使用多个数组对象访问JSON数据: android

标签 java android json

我陷入了从具有多个数据集的 JSON 文件中获取数据的困境。

{
  "status": "ok",
  "count": 3,
  "count_total": 661,
  "pages": 133,
  "posts": [
    {
      "id": 20038,
      "type": "post",
      "slug": "xperia-launcher-download",
      "url": "http:\/\/missingtricks.net\/xperia-launcher-download\/",
      "status": "publish",
      "title": "Download Xperia Launcher app for Android (Latest Version)"
    },
    {
      "id": 94,
      "type": "post",
      "slug": "top-free-calling-apps-of-2014-year",
      "url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2014-year\/",
      "status": "publish",
      "title": "Best Free Calling Apps for Android November 2014"
    },
    {
      "id": 98,
      "type": "post",
      "slug": "top-free-calling-apps-of-2016-year",
      "url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2016-year\/",
      "status": "publish",
      "title": "Best Free Calling Apps for Android December 2016"
    }
  ]
}

我需要从上面的 JSON 文件访问标题、url 和状态。

@Override
    protected void onPostExecute(String result) {
        //this method will be running on UI thread

        pdLoading.dismiss();
        List<DataFish> data = new ArrayList<>();
        pdLoading.dismiss();
        try {
            JSONArray jArray = new JSONArray(result);
            // Extract data from json and store into ArrayList as class objects
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                DataFish fishData = new DataFish();
                fishData.status = json_data.getString("status");                 
                fishData.title = json_data.getString("url");                  
                fishData.sizeName = json_data.getString("title");
                data.add(fishData);
            }
        } catch (JSONException e) {
            Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            Log.d("Json","Exception = "+e.toString());
        }
    }

使用上面的代码我得到了一个 JSONException。

我应该如何访问 JSON 文件中的标题、状态和 url?

最佳答案

您必须获取位于 JSONObject 内的 JSONArray ,因此创建一个 JSONObject 并使用索引“posts”获取数组

1.) result 是一个 JSONObject,因此创建一个 JSONObject

2.) 获取索引值为“posts”的 JSONArray

3.) 现在只需通过索引获取数组对象即可遍历数组对象

        JSONObject jObj = new JSONObject(result);
        JSONArray jArray = jObj.getJSONArray("posts");

        // Extract data from json and store into ArrayList as class objects
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json_data = jArray.getJSONObject(i);


            DataFish fishData = new DataFish();
            fishData.status = json_data.getString("status");

            fishData.title = json_data.getString("url");

            fishData.sizeName = json_data.getString("title");


            data.add(fishData);
        }

注意:我不知道它是否是一个较短版本的示例响应,尽管您的 json 对象应该以 } 结尾,而不是 , .

[{"id":20038,"type":"post","slug":"xperia-launcher-download","url":"http://missingtricks.net/xperia-launcher-download/","status":"publish","title":"Download Xperia Launcher app for Android (Latest Version)",

//  ^^^ there should be a } not a , to end json
// so make sure to do the correction so it will look like =>  ...st Version)"}, 

{"id":94,"type":"post","slug":"top-free-calling-apps-of-2014-year","url":"http://missingtricks.net/top-free-calling-apps-of-2014-year/","status":"publish","title":"Best Free Calling Apps for Android November 2014", ]

改进:

如果没有映射键,您可以使用optString来避免空值或非字符串值

这有两种变体

Get an optional string associated with a key. It returns the defaultValue if there is no such key.

 public String optString(String key, String defaultValue) {
  fishData.status = json_data.optString("status","N/A");
 // will return "N/A" if no key found 

或者如果没有找到键则获取空字符串,然后只需使用

  fishData.status = json_data.optString("status");
 // will return "" if no key found where "" is an empty string

关于java - 如何使用多个数组对象访问JSON数据: android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40817463/

相关文章:

java - 从 eclipse-update-site 升级到 eclipse-repository Maven 打包时出错

android - 如何在android中用不透明度填充矩形

android - 使用 Google Play 服务获取最后已知位置

javascript - 使用 d3 渲染 geoJSON

java - android java Map与自定义BiFunction合并

java - 获取 messages.log 风格的嵌入式 Neo4j 注销

objective-c - 使用 RESTKit 做一个简单的 json POST

java - 使用 gson 包解析嵌套的 json 结构

java - 如何在同一台机器上用Java测试广播udp包?

安卓工作室错误 :An existing connection was forcibly closed by the remote host