首页 > 解决方案 > 如何检查结果中的“评分”字段是否来自 Google Place Search?

问题描述

我想在回收站视图中显示我所在位置半径内的餐厅列表。所以,我使用了 Google Place Search API:

 https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=12.5074836,74.988503&radius=5000&type=restaurant&key=<MY_API_KEY>

我得到的结果很好。我在循环中使用以下代码将返回的结果建模为 Restaurant 类并将其添加到列表中:

Restaurant restaurant = new Restaurant(
   predsJsonArray.getJSONObject(i).getString("reference"),
   predsJsonArray.getJSONObject(i).getString("name"),
   predsJsonArray.getJSONObject(i).getString("vicinity"),
   predsJsonArray.getJSONObject(i).getString("icon"),
   predsJsonArray.getJSONObject(i).getDouble("rating"));
resultList.add(restaurant);

但是,在列表中添加了一些项目后,我得到了以下异常:

org.json.JSONException: No value for rating

于是,我意识到,可能不是每个结果都有rating字段。所以我的问题是,有没有办法将结果过滤到只有rating作为字段的地方,或者有没有办法检查rating结果中是否存在字段

标签: javaandroidgoogle-places-api

解决方案


你可以使用has这样的方法:

if (predsJsonArray.getJSONObject(i).has("rating")){

            // here it is safe to use predsJsonArray.getJSONObject(i).getDouble("rating")

    Restaurant restaurant = new Restaurant(
       predsJsonArray.getJSONObject(i).getString("reference"),
       predsJsonArray.getJSONObject(i).getString("name"),
       predsJsonArray.getJSONObject(i).getString("vicinity"),
       predsJsonArray.getJSONObject(i).getString("icon"),
       predsJsonArray.getJSONObject(i).getDouble("rating"));
    resultList.add(restaurant);
        }

推荐阅读