json - 如何在 Swift/Xcode 中解析来自 Google Places API 的 JSON“附近搜索响应”
问题描述
Google Maps API 运行良好,我得到了适当的 JSON 响应。但是,我无法解析错综复杂的 JSON 响应以获取我需要的特定信息,例如位置名称。我基本上浏览了我能找到的所有 YouTube 教程和在线帖子,但没有任何帮助。我已经包含了我正在使用的当前代码以及一个指向概述我得到的 JSON 响应的文档的链接。任何帮助将非常感激!
https://developers.google.com/places/web-service/search#nearby-search-and-text-search-responses
func nearbyLocations(latitude: Double, longitude: Double) {
let jsonUrlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(latitude),\(longitude)&radius=25&key=..."
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, respone, err) in
guard let data = data else { return }
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else { return }
print(json)
} catch let jsonErr {
print("json error:", jsonErr)
}
}.resume()
}
解决方案
您可以解析正常,如:
if let results = json["results"] as! [[String:Any]], let firstResult = results.first {
let geometry = firstResult["geometry"] as! [String:Any]
let location = geometry["location"] as! [String:Any]
let lat = location["lat"] as! Double
let lng = location["lng"] as! Double
}
推荐阅读
- android - 在 Android 应用程序的 ViewGroup 的“onInterceptTouchEvent”方法中,ACTION_MOVE 事件能否在 ACTION_DOWN 事件之前到达?
- c++ - 在 C++ 中使用 while 循环查找一组数字中的最小值的程序
- html - 视频 I 帧在移动浏览器上无法正常工作
- r - 如何使用 R 将每小时乘客 OD 数据传输到 od 矩阵
- android - 安装失败并显示消息无法提交安装会话
- python - 子集多索引列
- kubernetes - 当节点在 Kubernetes 上出现故障时如何运行脚本?
- python - Python CGI 脚本正在下载而不是运行
- javascript - 使用jquery在表格行的div中显示/隐藏图标
- c# - TestStack.White 不能点击菜单栏项目?