【问题标题】:Swift Codable can not Customize only the desired keysSwift Codable 不能只自定义所需的键
【发布时间】:2018-10-22 10:17:53
【问题描述】:

我只需要为下面的类手动自定义一个编码键

@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 枚举中,只是将标题覆盖为“名称”。

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

【问题讨论】:

  • 你使用哪个 Xcode 版本?
  • Xcode 10.0 版
  • swift 4.2 ??.....
  • 是........
  • 不,你不能。如果您必须映射一个键,则必须指定全部,但您可以将多个案例放在一行中,例如case body, publisher, url

标签: ios iphone swift realm


【解决方案1】:

适用于 Xcode 9.3 或更高版本

您可以通过结合 3 件事来实现:

  • 一个GenericCodingKeys 结构,允许我们使用任意字符串值创建编码键。
  • 将 JSON 键映射到您的属性名称的函数 (nametitle)
  • JSONDecoder 对象上设置keyDecodingStrategy = .custom(...)

试试这个:

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)

【讨论】:

    猜你喜欢
    • 2020-05-30
    • 2018-11-15
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2015-03-16
    • 2020-02-04
    • 2018-10-27
    相关资源
    最近更新 更多