Swift中如何解码存在类型不固定字段(String/Int/Null)的JSON数据?
解决方案
以下是两种常用的适配实现方式:
方案1:自定义解码逻辑,统一将value转为String类型存储
适合不需要保留value原始类型、只需要获取字符串形式值的场景,改动最小,兼容你原本的属性定义:
class ExampleClassToDecode: Decodable { let type: String let value: String? enum CodingKeys: String, CodingKey { case type, value } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) type = try container.decode(String.self, forKey: .type) // 按优先级尝试不同类型解码 if let stringValue = try? container.decode(String.self, forKey: .value) { value = stringValue } else if let intValue = try? container.decode(Int.self, forKey: .value) { value = "\(intValue)" } else { // 解码失败或为Null时赋值为nil value = nil } } }
方案2:定义多类型枚举承载value,保留原始类型信息
如果业务需要区分value是字符串、整型还是空值,可以先定义兼容多类型的Decodable枚举:
enum ValueType: Decodable { case string(String) case int(Int) case null init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let stringVal = try? container.decode(String.self) { self = .string(stringVal) return } if let intVal = try? container.decode(Int.self) { self = .int(intVal) return } if container.decodeNil() { self = .null return } throw DecodingError.dataCorruptedError(in: container, debugDescription: "value字段为不支持的类型") } }
修改原解码类的属性定义即可:
class ExampleClassToDecode: Decodable { let type: String let value: ValueType }
使用时按需取对应类型的值即可:
switch exampleObj.value { case .string(let str): print("字符串值:\(str)") case .int(let int): print("整型值:\(int)") case .null: print("value为空") }
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

