-2

我使用 Volley 库向 Google Places 发出 API 请求。响应是这样的对象:

{
    "html_attributions": [],
    "results": [
        {
          "address":  "Wood Quay, Dublin, Ireland",
          "name":     "Christ Church Cathedral",
          "place_id": "ChIJGw9ASiYMZ0gRy9yiaCZxNZI",
        },
        { ... },
        { ... },
    ],
    "status": "OK"
}

在里面Response.Listener我需要访问“结果”数组。
我尝试获取名称为“results”的 JSONArray,如下所示:

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API_URL, null,
        new Response.Listener <JSONObject> () {
            @Override
            public void onResponse(JSONObject response) {

                // THE PROBLEM IS HERE - WON'T COMPILE !!!
                JSONArray array = response.getJSONArray("results");
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //
            }
        });

但我看到一个错误: 在此处输入图像描述

4

1 回答 1

2

好像response.getJSONArray("results");扔了JSONException。您需要通过response.getJSONArray("results");使用 try-catch 块包装来处理该异常。

像这样的东西:

 try {
    JSONArray array = response.getJSONArray("results");
} catch (org.json.JSONException exception) {
    //  handle the exception
}
于 2019-01-16T23:12:55.713 回答