0

我有这个(恕我直言)JSON

"geometry": {
        "type": "Point",
        "coordinates": [
          6.08235,
          44.62117
        ]
}

我想映射到 this struct,删除 2 个字段的数组。

struct MMGeometry:Codable {
    let type:String
    let latitude: Double
    let longitude: Double
}

JSONDecoder能力做到这一点吗?也许使用CodingKey?

4

1 回答 1

1

我选择了手动解决方案:

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 {

    }
}
于 2017-07-26T21:40:12.263 回答