如何检查 'rating' 字段是否出现在 Google Place Search 的结果中?
How to check if the 'rating' field in present in the results got from Google Place Search?
我想在 recyclerview 中显示我所在位置半径范围内的餐馆列表。所以,我使用了 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 class 并将其添加到列表中:
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);
}
我想在 recyclerview 中显示我所在位置半径范围内的餐馆列表。所以,我使用了 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 class 并将其添加到列表中:
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);
}