I'm trying to parse a JSON, hope you guys can help me out. How would I decode this in swift 4? I need to get the value inside the second set of coordinates that don't have a type. This is a the JSON code:
{
"geo": [{
"area": 153.2295,
"tipo": "ARL_TOTAL",
"geoJson": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-54.869875405035, -7.7332162703037],
[-54.87000906538, -7.7333509322313],
[-54.870081208559, -7.7334236160148]
]
],
[
[
[-54.866741527372, -7.7218185563672],
[-54.869847964562, -7.733188624206],
[-54.866741527372, -7.7218185563672]
]
]
]
}
}]
}
I you want to access the coordinates, you could do something like this:
struct NestedJSON: Codable {
let type: String
let coordinates: [[[[Double]]]]
}
struct Area: Codable {
let area: Double
let tipo: String
let geoJson: NestedJSON
}
struct JSONExample: Codable {
let geo: [Area]
}
if let url = Bundle.main.url(forResource: "example", withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let json = try? JSONDecoder().decode(JSONExample.self, from: data)
json?.geo.first?.geoJson.coordinates
.compactMap {$0}
.forEach { print($0.flatMap {$0}) }
} catch {
print("error:\(error)")
}
}
You would need to play around a bit with your coordinates
object, you can use Playgrounds for it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.