你可以做类似的事情: -
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
}
}
}
这里的值可以是三种类型,我手动识别它是哪种类型。