Matthieu Riegler
Matthieu Riegler

Reputation: 55836

Codable: Decode a JSONArray to specific fields by index

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

Answers (1)

Matthieu Riegler
Matthieu Riegler

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

Related Questions