在处理多态 JSON(如不同 type 字段对应不同子类)时,如何实现自定义解码?
解读
国内 iOS 面试中,多态 JSON 解码是“必考高频”。
- 场景真实:后端为了减少接口数量,常把多种模型塞进同一个数组,靠 type 字段区分。
- 考点综合:既考 Codable 协议深度,又考 Swift 类型系统、错误处理、性能与可维护性。
- 评判标准:
- 能说出“为什么不用 Any/NSDictionary”——类型安全。
- 能写出“可扩展、可测试、无样板”的解码方案。
- 能对比三种以上实现路径的优劣,并给出线上踩坑经验(如后端新增 type 未同步导致 crash)。
知识点
- Codable 协议栈:Decodable 的 init(from:) 与 KeyedDecodingContainer。
- 类型擦除与运行时:Swift 无 Objective-C 的 Runtime,不能靠字符串直接转类,需要“工厂表”或“注册中心”。
- 错误模型:DecodingError.typeMismatch / keyNotFound / valueNotFound,必须包装成业务错误,方便埋点与灰度。
- 泛型与关联类型:利用协议关联类型把“解析”与“模型”解耦,实现编译期类型安全。
- 性能与二进制大小:
- 避免在 decode 阶段反复 switch/case 字符串;
- 用静态字典缓存闭包,减少运行时反射。
- 向后兼容:
- 后端新增 type 时,客户端不升级不能闪退;
- 采用“空实现模型 + 日志上报”策略。
答案
给出“注册中心 + 协议约束”的工业级模板,可直接搬进项目。
import Foundation
// MARK: - 1. 协议层:定义多态契约
protocol PolyDecodable: Decodable {
/// 后端 type 字段的原始值
static var jsonType: String { get }
}
// MARK: - 2. 工厂层:运行时注册表
enum PolyDecoderFactory {
private static var map: [String: PolyDecodable.Type] = [:]
/// 在 App 启动或模块初始化时调用,保证注册顺序可控
static func register(_ type: PolyDecodable.Type) {
map[type.jsonType] = type
}
static func decode(_ container: KeyedDecodingContainer<PolyBaseCodingKeys>,
from decoder: Decoder) throws -> PolyBase {
let typeKey = try container.decode(String.self, forKey: .type)
guard let RealType = map[typeKey] else {
// 线上容错:返回空模型并上报
#if DEBUG
throw DecodingError.dataCorruptedError(forKey: .type,
in: container,
debugDescription: "未注册的 type: \(typeKey)")
#else
return UnknownPolyModel(type: typeKey)
#endif
}
return try RealType.init(from: decoder)
}
}
// MARK: - 3. 基模型层:统一入口
class PolyBase: PolyDecodable {
required init(from decoder: Decoder) throws {
// 子类必须重写,基类只做分发
fatalError("Use subclass")
}
// 默认实现,防止子类忘记写
static var jsonType: String { "" }
}
// MARK: - 4. 具体模型层
final class ImageModel: PolyBase {
static let jsonType = "image"
let url: URL
let width: Int
let height: Int
private enum CodingKeys: String, CodingKey {
case url, width, height
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
url = try container.decode(URL.self, forKey: .url)
width = try container.decode(Int.self, forKey: .width)
height = try container.decode(Int.self, forKey: .height)
super.init()
}
}
final class VideoModel: PolyBase {
static let jsonType = "video"
let url: URL
let duration: TimeInterval
private enum CodingKeys: String, CodingKey {
case url, duration
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
url = try container.decode(URL.self, forKey: .url)
duration = try container.decode(TimeInterval.self, forKey: .duration)
super.init()
}
}
// 未知类型兜底
final class UnknownPolyModel: PolyBase {
let type: String
init(type: String) {
self.type = type
super.init()
}
required init(from decoder: Decoder) throws {
fatalError("UnknownPolyModel 不通过 decoder 初始化")
}
}
// MARK: - 5. 容器层:数组解码
struct Feed: Decodable {
let items: [PolyBase]
private enum CodingKeys: String, CodingKey {
case items
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var itemsArray = try container.nestedUnkeyedContainer(forKey: .items)
var tmp: [PolyBase] = []
while !itemsArray.isAtEnd {
let itemDecoder = try itemsArray.superDecoder()
let single = try itemDecoder.singleValueContainer()
let baseContainer = try itemDecoder.container(keyedBy: PolyBaseCodingKeys.self)
let model = try PolyDecoderFactory.decode(baseContainer, from: itemDecoder)
tmp.append(model)
}
items = tmp
}
}
// 公共 key
private struct PolyBaseCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) { self.stringValue = stringValue }
var intValue: Int?
init?(intValue: Int) { return nil }
static let type = PolyBaseCodingKeys(stringValue: "type")!
}
// MARK: - 6. 启动注册
extension PolyDecoderFactory {
static func warmUp() {
register(ImageModel.self)
register(VideoModel.self)
}
}
使用方式:
PolyDecoderFactory.warmUp()
let json = """
{
"items": [
{ "type": "image", "url": "https://a.com/a.jpg", "width": 100, "height": 200 },
{ "type": "video", "url": "https://b.com/b.mp4", "duration": 120 }
]
}
""".data(using: .utf8)!
let feed = try JSONDecoder().decode(Feed.self, from: json)
feed.items.forEach { print(type(of: $0)) } // ImageModel / VideoModel
亮点总结:
- 零反射,纯静态注册,编译期检查。
- 新增模型只需三步:写模型 → 实现 PolyDecodable → 注册,无需改旧代码。
- 线上容错,未知 type 不闪退,方便灰度与埋点。
拓展思考
-
如果后端返回的 type 字段层级更深(如嵌套在 meta.type),如何不改工厂代码就能适配?
→ 在 PolyBaseCodingKeys 中增加嵌套 Key 路径,用 KeyedDecodingContainer 的 nestedContainer 一次性取出,工厂接口保持不变。 -
当模型数量暴涨到 100+,启动注册会影响冷启动时间?
→ 把注册改为懒加载:首次遇到未缓存的 type 时,通过 Swift 的 _typeByName 动态加载并注册,同时把结果缓存到本地 plist,下次启动直接读取缓存。 -
若需要支持 Swift Concurrency 的 JSON 流式解析(如 JSON Lines),如何改造?
→ 利用 AsyncSequence 包装 JSONDecoder,每读到一条就调用 PolyDecoderFactory.decode,配合 TaskGroup 实现并发解码,注意 Actor 隔离避免数据竞争。