ios - Swift Codable 无法仅自定义所需的按键

标签 ios iphone swift realm

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

@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 结构,允许我们使用任意字符串值创建编码 key 。
  • 将 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/

相关文章:

ios - 接受 ios 应用程序付款?

iphone - IOS : setting 'dimmer' view's alpha to greater than 0. 0 禁用触摸事件(?)

ios - UILabel:智能换行(动态)

ios - 以编程方式快速切换另一个导航

ios - UIScrollView subview 未扩展到填充宽度(自动布局)

c# - MonoTouch-XCode的组织器中更好的控制台输出

ios - CLLocation 变量不发送 KVO - NSKeyValueObservingOptionNew

iphone - datepicker 给出 UIControlEventValueChanged 无法识别的选择器错误

iPhone:如何以编程方式回复短信

ios - 以一定角度将文本绘制到图像上 [Swift 3]