从AF ResponseJSON获取数据

时间:2019-04-24 13:38:14

标签: swift alamofire

我有处理位置数据的代码,因此我可以提取可以匿名化数据的详细信息-例如,如果我的places API表示它是_type:“建筑物”,而建筑物:“ Safeway”,则可以保存数据作为经/纬度的“ md5”:“安全路”,并且在检查我的位置数据时所有安全路看起来都一样。这也是我想要的。

static func getLocationData(location: CLLocation, _ callback: @escaping (CLLocation?) -> Void) {
    let parameters = [
            "q": location.coordinate.latitude.description + "," + location.coordinate.longitude.description,
            "key": Places.OPENCAGEDATA_API_KEY
        ]

    AF.request(Places.uri, method: .get, parameters: parameters, encoding: URLEncoding(destination: .queryString)).responseJSON { response in
        switch response.result {

        case .success(let json):
            print(json)
            DispatchQueue.main.async {

               callback(location)

            }
        case .failure(let error):
            print(error)

            callback(nil)
        }
    }
}

此交易有效,如我所见:

{
    documentation = "https://opencagedata.com/api";
    licenses =     (
                {
            name = "CC-BY-SA";
            url = "https://creativecommons.org/licenses/by-sa/3.0/";
        },
                {
            name = ODbL;
            url = "https://opendatacommons.org/licenses/odbl/summary/";
        }
    );
    rate =     {
        limit = 2500;
        remaining = 2496;
        reset = 1556150400;
    };
    results =     (
                {
            annotations =             {
                DMS =                 {
                    lat = "MYLAT N";
                    lng = "MYLONG W";
                };
                FIPS = ...

但是现在json只是类型恰好可以很好打印的Any。我怎么会得到json.results.annotations.DMS.lat

2 个答案:

答案 0 :(得分:2)

您可以尝试

 if let res = json as? [String: Any]{
    if let inner = res["results"] as? [[String: Any]] {
        for item in inner {
            if let ert = item["annotations"] as? [[String: Any]] {
                for ann in ert {
                    print(ann["lat"])
                }
            }
        }
    }
}

您也可以

struct Root: Codable {
    let results: [DataClass] 
}

struct DataClass: Codable {
    let annotations: [Anno]
}

struct Anno: Codable {
    let lat:Double // or String as in your question it's a String IDN if this is a description
}

        do {
             guard let data = try JSONSerialization.data(withJSONObject: json, options: []) else { return } 
            let locationObject = try JSONDecoder().decode(Root.self, from:data)
        } catch  {
            print(error)
        }

答案 1 :(得分:0)

这应该有帮助:

AF.request(Places.uri, method: .get, parameters: parameters, encoding: URLEncoding(destination: .queryString)).responseString { response in
    switch response.result {

    case .success(let json):
        print(json)
        if let returnedValue = responseObject.result.value, !returnedValue.isEmpty {
            do {
                let locationObject = try JSONDecoder().decode(Location.self, from: (returnedValue.data(using: .utf8))!)
            } catch let e {
                print("Couldn't Parse data because... \(e)")
            }
        }
        DispatchQueue.main.async {

           callback(location)

        }
    case .failure(let error):
        print(error)

        callback(nil)
    }
}
相关问题