Swift带关联值枚举配合Codable解析多类型JSON字段失败如何解决?
问题根源
你当前的Value枚举的Codable实现采用了键编码格式,要求输入JSON的value字段必须携带对应枚举case的外层标识key,比如要求格式为{"str": "xxx"}或者{"event": {"name": "fff"}}。但你实际传入的JSON中value是直接放置原始值/业务对象,没有外层case标识,所以解码时读取CodingKeys对应的键值容器会找不到任何匹配key,导致container.allKeys为空,最终进入default分支抛出错误。
修复方案
将Value枚举的编解码逻辑改为无键类型推断实现:解码时按优先级依次尝试匹配4种允许的类型,编码时直接输出关联值本身,不需要外层key包装。
修正后的完整Value枚举代码如下:
enum Value: Codable { case str(String) case formField(FormField) case passType(PassType) case event(Event) func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case let .str(string): try container.encode(string) case let .formField(field): try container.encode(field) case let .passType(field): try container.encode(field) case let .event(field): try container.encode(field) } } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() // 可根据实际业务场景调整解码尝试的优先级 if let str = try? container.decode(String.self) { self = .str(str) return } if let event = try? container.decode(Event.self) { self = .event(event) return } if let formField = try? container.decode(FormField.self) { self = .formField(formField) return } if let passType = try? container.decode(PassType.self) { self = .passType(passType) return } throw DecodingError.dataCorrupted( .init( codingPath: container.codingPath, debugDescription: "value字段不匹配任意支持的类型" ) ) } }
内容的提问来源于stack exchange,提问作者János
相关产品推荐
相关产品推荐

