get data from AF responseJSON

荒凉一梦 提交于 2020-01-06 06:27:00

问题


I have code to process location data so I can extract details that can anonymize the data -- for example, if my places API says it is a _type: "Building" and building: "Safeway" -- I could save the data as an md5 of the lat/long:"safeway", and all safeways would look the same when inspecting my location data. That's also what I want.

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

This transaction works, as I see printed:

{
    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 = ...

But now json is just a type Any that happens to print nicely. How would I get , for example, json.results.annotations.DMS.lat?


回答1:


This should help :

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



回答2:


You can try

 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"])
                }
            }
        }
    }
}

Also you can do

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


来源:https://stackoverflow.com/questions/55831439/get-data-from-af-responsejson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!