Reputation: 55836
I have this (imho shitty) JSON
"geometry": {
"type": "Point",
"coordinates": [
6.08235,
44.62117
]
}
I wanted to map to this struct
, dropping the array for 2 fields.
struct MMGeometry:Codable {
let type:String
let latitude: Double
let longitude: Double
}
Is the JSONDecoder
able to do this ? Maybe using a CodingKey
?
Upvotes: 0
Views: 433
Reputation: 55836
I went for the manual solution :
struct Geometry:Codable {
let type:String
let latitude: Double
let longitude: Double
enum CodingKeys: String, CodingKey {
case type, coordinates
}
enum CoordinatesKeys: String, CodingKey {
case latitude, longitude
}
init (from decoder :Decoder ) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
type = try container.decode(String.self, forKey: .type)
let coords:[Double] = try container.decode([Double].self, forKey: .coordinates)
if coords.count != 2 { throw DecodingError.dataCorruptedError(forKey: CodingKeys.coordinates, in: container, debugDescription:"Invalid Coordinates") }
latitude = coords[1]
longitude = coords[0]
}
func encode(to encoder: Encoder) throws {
}
}
Upvotes: 1