ios - 如何手动对选定的按键进行解码,以及如何利用快速解码功能自动解码呢?

标签 ios swift codable decodable encodable

这是我正在使用的代码,

struct CreatePostResponseModel : Codable{
    var transcodeId:String?
    var id:String = ""
    enum TopLevelCodingKeys: String, CodingKey {
        case _transcode = "_transcode"
        case _transcoder = "_transcoder"
    }
    enum CodingKeys:String, CodingKey{
        case id = "_id"
    }
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: TopLevelCodingKeys.self)
        if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcode) {
            self.transcodeId = transcodeId
        }else if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcoder) {
            self.transcodeId = transcodeId
        }

    }
}

在这里,transcodeId_transcode_transcoder决定。
但我希望id和其余键(此处未包括)可以自动解码。我该怎么做 ?

最佳答案

一旦以init(from:)类型实现Codable,就需要手动解析所有键。

struct CreatePostResponseModel: Decodable {
    var transcodeId: String?
    var id: String

    enum CodingKeys:String, CodingKey{
        case id, transcode, transcoder
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decodeIfPresent(String.self, forKey: .id) ?? ""
        if let transcodeId = try container.decodeIfPresent(String.self, forKey: .transcode) {
            self.transcodeId = transcodeId
        } else if let transcodeId = try container.decodeIfPresent(String.self, forKey: .transcoder) {
            self.transcodeId = transcodeId
        }
    }
}

在上面的代码中,
  • 如果只想解码JSON,则无需使用Codable。使用Decodable就足够了。
  • 这里似乎不需要为enums使用多个CodingKey。您可以使用一个enum CodingKeys
  • 如果属性名称和键名称完全匹配,则无需在rawValue中显式指定该caseenum CodingKeys。因此,"_transcode"中不需要"_transcoder"rawValues TopLevelCodingKeys

  • 除此之外,您还可以将keyDecodingStrategy用作.convertFromSnakeCase来处理下划线表示法( snake case表示法),即
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase //here.....
        let model = try decoder.decode(CreatePostResponseModel.self, from: data)
        print(model)
    } catch {
        print(error)
    }
    

    因此,您无需显式处理所有蛇形键。它将由JSONDecoder自行处理。

    关于ios - 如何手动对选定的按键进行解码,以及如何利用快速解码功能自动解码呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57215567/

    相关文章:

    android - 在 ionic LaunchNavigator.navigate 中使用坐标而不是城市文本

    android - 与 Jenkins 持续集成用于 React Native (iOS + Android) 项目

    ios - 如何使 UIView 动画序列重复和自动反转

    swift - 查找与 OptionSet 的值关联的名称

    ios - Xcode 11 单元测试 : Devices with iOS 12. * 未列出

    json - 如何使用 swift 4 和 struct 从字典中获取数据?

    ios - 自定义 UITableViewCell 中的 UIButton 导致在多个单元格中选择按钮

    arrays - 如何在 Swift 的 View Controller 类中与 Collection View 委托(delegate)共享数据

    ios - 在 Decodable 解码函数中检索 JSON 字符串

    swift - 将可解析结构转换为可编码结构无法按预期工作