如何检查结果中的"评分"字段是否来自 Google 地点搜索?



我想在回收视图中显示我所在位置半径范围内的餐厅列表。因此,我使用了谷歌搜索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字段

您可以像这样使用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);
}

最新更新