首页 > 解决方案 > 如何在 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()
}

标签: jsonswiftxcodegoogle-mapsparsing

解决方案


您可以解析正常,如:


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
}

推荐阅读