我只需要为以下 class 手动自定义一个编码键

@objcMembers class Article :Object, Decodable{
        dynamic var id: Int = 0
        dynamic var title: String = ""
        dynamic var image: String = ""
        dynamic var author : String = ""
        dynamic var datePublished: Date?
        dynamic var body: String?
        dynamic var publisher: String?
        dynamic var url: String?

    }

所以我必须添加以下枚举
private enum CodingKeys: String, CodingKey {
        case id
        case title = "name"
        case image
        case author
        case datePublished
        case body
        case publisher
        case url
    }

因此,我将所有类成员都添加到了CodingKeys枚举中,以便仅将标题覆盖为“name”。

有什么办法可以让我仅将要自定义的案例添加到枚举中???

最佳答案

对于Xcode 9.3或更高版本

您可以通过结合以下三点来实现:

  • 一个GenericCodingKeys结构,可让我们制作具有任意字符串值的编码键。
  • 一个将JSON键映射到您的属性名称的函数(nametitle)
  • keyDecodingStrategy = .custom(...)对象
  • 上设置 JSONDecoder

    试试这个:
    import Foundation
    
    // A struct that allows us to construct arbitrary coding keys
    // You can think of it like a wrapper around a string value
    struct GenericCodingKeys: CodingKey {
        var stringValue: String
        var intValue: Int?
    
        init?(stringValue: String) { self.stringValue = stringValue }
        init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
    }
    
    @objcMembers class Article: NSObject, Decodable {
        dynamic var id: Int = 0
        dynamic var title: String = ""
        dynamic var image: String = ""
        dynamic var author : String = ""
        dynamic var datePublished: Date?
        dynamic var body: String?
        dynamic var publisher: String?
        dynamic var url: String?
    
        static func codingKeyMapper(path: [CodingKey]) -> CodingKey {
            // `name` is the key in JSON. `title` is your property name
            // Here, we map `name` --> `title`
            if path.count == 1 && path[0].stringValue == "name" {
                return GenericCodingKeys(stringValue: "title")!
            } else {
                return path.last!
            }
        }
    }
    
    let json = """
    {
        "id": 1,
        "name": "A title",
        "image": "An image",
        "author": "Any author",
    }
    """.data(using: .utf8)!
    
    // Configure the decoder object to use a custom key decoding strategy
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .custom(Article.codingKeyMapper)
    let article = try decoder.decode(Article.self, from: json)
    
    print(article.title)
    

    关于ios - Swift Codable不能仅自定义所需的键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52926987/

    10-12 12:36
    查看更多