java - 如何检查结果中的“评分”字段是否来自 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
结果中是否存在字段?
解决方案
你可以使用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);
}
推荐阅读
- react-native - 如何在 React Native 中将计时器重置为 0?
- symfony - 如何访问最初提交的 Symfony 表单数据?
- javascript - 在 setTimeout 方法中渲染组件不起作用
- c - 可以将库中的 .text、.data、.bss .a 文件分成单独的部分吗
- chat - 如何在玩家加入我的游戏时显示聊天消息
- c# - Gmap.net 将路线转换为点
- javascript - Jquery自动完成框并不总是有效
- anylogic - Anylogic M/M/2/[4] 系统模拟不正确?
- node.js - Docker 容器无法安装 NPM 包
- laravel - Laravel Blade:如何获取父 URL