Skip to content

Instantly share code, notes, and snippets.

@gavi
Last active February 1, 2023 14:27
Show Gist options
  • Save gavi/3555ea38431e1b715f7152c7dd7ce45e to your computer and use it in GitHub Desktop.
Save gavi/3555ea38431e1b715f7152c7dd7ce45e to your computer and use it in GitHub Desktop.
Parsing Nested JSON Structure in Swift
import Foundation
let geoResult="""
{
"results": [
{
"formatted_address": "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry": {
"location": {
"lat": 37.4224764,
"lng": -122.0842499
}
}
}
],
"status": "OK"
}
""".data(using: .utf8)!
struct GeocodingService:Codable{
var status:String
var results:[GeocodingResult]
}
struct GeocodingResult:Codable{
struct Geometry:Codable{
struct Location:Codable{
let lat:Float
let lng:Float
}
let location:Location
}
let formatted_address:String
let geometry:Geometry
}
let decoder=JSONDecoder()
do{
let obj=try decoder.decode(GeocodingService.self, from: geoResult)
for result in obj.results{
print("(\(result.geometry.location.lat),\(result.geometry.location.lng))")
}
}catch{
print("\(error)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment