Alamofire:具有额外 属性 的 Codable 对象

Alamofire: Codable object with extra property

我有一个 Codable 对象模型,我正在使用 Alamofire 检索它。但是我想在模型中添加额外的布尔变量,这不是服务器端模型的一部分,这在 iOS 上可能吗?

为了符合 Codable 协议,我需要将它添加到 CodingKeys 枚举中,但如果我这样做,它会尝试从不存在的服务器解析 属性。

您可以简单地为 属性 提供一个默认值,它只应存在于您的 iOS 应用程序的模型 class 中,然后从中省略 属性 的名称你的 CodingKey enum 和你的模型 class/struct 仍然会符合 Codable 而不必 encode/decode 属性 to/from JSON.

您可以在下面找到这方面的示例。

struct Person: Decodable {
    let name:String
    let age:Int
    var cached = false //not part of the JSON

    enum CodingKeys:String,CodingKey {
        case name, age
    }
}

let json = """
{"name":"John",
"age":22}
"""

do {
    let person = try JSONDecoder().decode(Person.self,from: json.data(using: .utf8)!)
    print(person) // Person(name: "John", age: 22, cached: false)
} catch {
    print(error)
}