I need to access lat and lng. How can I do that?
This is what I do now, and it doesn't work:
latitude <- map["location"]["lat"]
longitude <- map["location"]["lng"]
I need to access lat and lng. How can I do that?
This is what I do now, and it doesn't work:
latitude <- map["location"]["lat"]
longitude <- map["location"]["lng"]
You just simply need:
latitude <- map["location.lat"]
longitude <- map["location.lng"]
So far ObjectMapper supports dot notation within keys for easy mapping of nested objects (you could find it under "Easy Mapping of Nested Objects" in library documentation).
You would need to declare a separated class for the location to contain the lat and the lng properties:
class Location: Mappable {
var lat: Double?
var lng: Double?
required init?(map: Map){ }
func mapping(map: Map) {
lat <- map["lat"]
lng <- map["lng"]
}
}
thus you could use it as:
class Base: Mappable {
var location: Location?
// ...
required init?(map: Map){ }
func mapping(map: Map) {
location <- map["location"]
//...
}
}
It would represent a nested type for mapping the base object.
Aside bar note: you might also want to check Codable - Encoding and Decoding Custom Types.
Instead of using ObjectMapper , you can use JSONDecoder , that will enable you to write only the key of the objects inside the json , instead of writing them twice with ObjectMapper. (as a property and inside map function ) , especially if the server keys naming is suitable for you
Hope this helps you
let data = NSData(contentsOf: searchUrl as URL)
let json = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject]
let status = json["status"] as! String
print(status)
if status == "OK" {
if let result = json["results"] as? [[String:AnyObject]] {
if let geometry = result[0]["geometry"] as? [String:AnyObject] {
if let location = geometry["location"] as? [String:AnyObject] {
lat = location["lat"] as! Double
lng = location["lng"] as! Double
print(lat)
print(lng)
}
}
}
JSONSerialization. Even so, your answer doesn't provide a correct result.