首页 > 解决方案 > JSON 数组中的参数

问题描述

我知道这可能在某处得到了解释,但我实际上还没有找到我要找的东西。我正在使用电影数据库 api 开发一个用于搜索电影的 android 应用程序。我也在使用 okhttp 和默认的 json (org.json)。我不太清楚如何在 api 返回给我的 json 中提取我想要的参数。

回报如下

{
    "total_results": x,
    "results": [
    {
      "popularity": xxxx,
      "id": xxxx,
      "title": "xxxx",
      "vote_average": 8,
      "overview": "xxxx",
    },
    {
      "popularity": xxxx,
      "id": xxxx,
      "title": "xxxx",
      "vote_average": 8,
      "overview": "xxxx",
    }]
}

我想保留上面的参数。我了解如何获得“total_results”,

@Override
public void run() {
int j=0;
     try {
          JSONObject json = new JSONObject(myResponse);

          j = json.getInt("total_results");
     } catch (JSONException e) {
          e.printStackTrace();
     }
     mTextViewResult.setText("Results: " + j);
}

但是我怎样才能得到“结果”中的参数呢?

标签: javaandroidjsonokhttp

解决方案


您应该使用 getJsonArray():

try {
        JSONObject json = new JSONObject(myResponse);

        j = json.getInt("total_results");
        JSONArray results = json.getJSONArray("results");
        for (int i=0; i<results.length(); i++) {
            JSONObject thisResult = results.getJSONObject(i);
            String thisTitle = thisResult.getString("title");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

推荐阅读