【问题标题】:How to parse JSON "nearby search response" from Google Places API in Swift/Xcode如何在 Swift/Xcode 中解析来自 Google Places API 的 JSON“附近搜索响应”
【发布时间】:2019-07-01 06:51:02
【问题描述】:

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()
}

【问题讨论】:

    标签: json swift xcode google-maps parsing


    【解决方案1】:

    你可以正常解析:

    
    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
    }
    

    【讨论】:

    • 没问题,祝你好运! :D
    【解决方案2】:

    使用 Codable 解析 JSON 响应

    型号:

    struct Root: Codable {
        var results: [SearchResult]
        var status: String
    }
    
    struct SearchResult: Codable {
        var id: String
        var icon: String
        var name: String
        var placeId: String
        var reference: String
        var types: [String]
        var vicinity: String
        var geometry: Geometry
        var photos: [Photo]
        var openingHours: [String:Bool]?
    }
    
    struct Geometry: Codable  {
        var location: Location
    }
    
    struct Location: Codable  {
        var lat: Double
        var lng: Double
    }
    
    struct Photo: Codable {
        var height: Double
        var width: Double
        var photoReference: String
    }
    

    在上述模型中,根据您的要求添加keys。此外,上述任何keys 都无法通过 API 确定,请将它们标记为 optional

    解析:

    解析你在URLSession.shared.dataTask中获得的datalike,

    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let root = try decoder.decode(Root.self, from: data)
        print(root)
    } catch {
        print(error)
    }
    

    用法:

    对于您提供的链接中的示例 JSON 响应,您可以使用 root 访问响应的属性,例如,

    root.status //OK
    
    root.results.first?.name //Rhythmboat Cruises
    
    root.results.first?.geometry.location.lat //-33.870775
    

    详细了解Codable 及其工作原理here

    【讨论】:

    • 如果答案有帮助,请接受(在左侧打勾)。此外,Codable 是一种非常有效和可读的方式,代码比 JSONSerialization 少得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 2020-08-28
    • 2019-12-14
    相关资源
    最近更新 更多