1

我有一个 Swift 应用程序,我正在转换它以使用 Codable 协议(而不是 EVReflection,它发生了很大的变化,以至于我无法再让它工作)。当与应用服务器进行交易时,我的代码生成一个“ServerResponse”类的对象,其中包含许多变量——其中一个是“responseObject”——它可以是从用户到消息的任意数量的不同对象,或其他。因为 Codable 默认情况下不使用“decodeIfPresent”,所以我在某些事务期间遇到错误,并且必须覆盖 init(来自解码器:解码器)以防止这种情况。现在,我面临的挑战是如何让原始 JSON 字符串保持完整,以便稍后通过调用方法解码为正确的对象类型,或者进行一些其他类似的修复。底线:

如果有人有任何建议,我将不胜感激。如果有帮助,我会很乐意分享代码,但我认为不会,因为这个问题本质上是概念性的。

4

1 回答 1

3

你可以做类似的事情: -

struct CustomAttribute: Codable {
var attributeCode: String?
var intValue: Int?
var stringValue: String?
var stringArrayValue: [String]?

enum CodingKeys: String, CodingKey {

    case attributeCode = "attribute_code"
    case intValue = "value"
    case stringValue
    case stringArrayValue
}

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)

    attributeCode = try values.decode(String.self, forKey: .attributeCode)
    if let string = try? values.decode(String.self, forKey: .intValue) {
        stringValue = string
    } else if let int = try? values.decode(Int.self, forKey: .intValue) {
        intValue = int
    } else if let intArray = try? values.decode([String].self, forKey: .intValue) {
        stringArrayValue = intArray
    }
}

}

这里的值可以是三种类型,我手动识别它是哪种类型。

于 2017-09-24T09:23:22.780 回答