Last active
February 1, 2023 14:27
-
-
Save gavi/3555ea38431e1b715f7152c7dd7ce45e to your computer and use it in GitHub Desktop.
Parsing Nested JSON Structure in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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