"geometry": {
"location": {
"lat": -33.8710748,
"lng": 151.1989921
},
"viewport": {
"northeast": {
"lat": -33.86946102010727,
"lng": 151.2000783298927
},
"southwest": {
"lat": -33.87216067989272,
"lng": 151.1973786701072
}
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id": "cbdb9bdfa9d40e704c628f261adeef9875a5ccd7",
"name": "Harbour Bar & Kitchen",
"opening_hours": {
"open_now": true
},
这是来自Google地图网址的json文件。我想将其解码为swift对象。我尝试了不同的方法,但没有一个起作用。下面的代码可以成功获取“名称”,但不能获取lat和lng。是否可以使用nestedContainer来获取lat和lng的值?
class VolumeData:NSObject, Decodable
{
var gyms:[GymData] ? private enum CodingKeys : String, CodingKey
{ case gyms = "results" }
}
class GymData:NSObject, Decodable
{
var lat:String ? var lng : String ? var name : String private enum
RootKeys:String, CodingKey
{
case name = "name" case geometry =
"geometry" enum NestedCodingKeys:String,
CodingKey
{ case lat = "lat" case lng = "lng" }
}
required init (from decoder:Decoder) throws
{
// Get the root container first
let rootContainer = try decoder.container (keyedBy:
RootKeys.self) let locContainer = try rootContainer.nestedContainer (keyedBy:RootKeys.NestedCodingKeys.self,
forKey: .geometry)
// let locContainer = try geoContainer.nestedContainer(keyedBy:
// GeoKeys.self, forKey: .location)
// Get the gym info
self.name = try rootContainer.decode (String.self, forKey:.name)
self.lat = try ? locContainer.decode (String.self, forKey :.lat)
self.lng = try ? locContainer.decode (String.self, forKey :.lng)
}
}