swift - Codable:通过索引将 JSONArray 解码为特定字段

标签 swift swift4 codable

我有这个(恕我直言)JSON

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

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

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

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

最佳答案

我选择了手动解决方案:

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 {

    }
}

关于swift - Codable:通过索引将 JSONArray 解码为特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45337686/

相关文章:

arrays - 合并自定义对象数组以形成新对象

swift - 使用 "self."前缀和在闭包的捕获列表中写入 "self"有什么区别?

swift - 在 Uitableviewcontroller 中创建水平滚动区域

arrays - Swift - 如何将 Any 转换为 Array\Dictionary?

ios - 在哪里存储来自服务器的解码 JSON 数组以及如何在 viewControllers 中全局访问它?

swift - SpriteKit - 创建变化的渐变

swift - 使用 MQTT 实现离线聊天

ios - 自定义 xib 在 super View 中大小不正确

swift - 无法修改 Codable 类属性?

ios - 如何在 Swift 4 中验证 JSON?