我有处理位置数据的代码,因此我可以提取可以对数据进行匿名化的详细信息 - 例如,如果我的places API说它是_type:“Building”并构建:“Safeway” - 我可以将数据保存为lat / long的md5:“safeway”,检查我的位置数据时所有安全通道看起来都一样。这也是我想要的。
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
?
这应该有所帮助:
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)
}
}
你可以试试
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)
}