如何为泛型类型 T 实现 Codable,使其能适应不同结构的 JSON?

解读

国内 iOS 面试中,这道题考察的不是“写个 struct 直接 Codable 就完事”的模板代码,而是“当 JSON 结构不可控、字段可能缺失、类型可能变化、甚至 key 名都不固定时,如何让一个泛型层(网络层、缓存层、中间件)仍然能透明地完成解析”的架构能力。
面试官通常会在追问环节给出三种变形:

  1. JSON 根节点可能是 {code:0,data:T} 也可能是 {status:"ok",result:T};
  2. data/result 里的字段名在不同接口里不一样;
  3. T 本身可能是 [Model]、Model、String 甚至嵌套了 Optional。
    如果候选人只回答 “T: Codable 就行”,会被认为“只写过业务层,没写过框架层”。正确姿势是:
  • 让泛型容器负责“剥掉”外层可变的包装;
  • 让 T 只关心自己那一层,不感知外层差异;
  • 用协议抽象“任何能剥出 T 的东西”,再用类型擦除或关联类型把具体策略注入编译期。
    最终达到:业务方只声明 APIRequest<User>,网络层自动适配任意 JSON 外壳,且编译期保证类型安全。

知识点

  1. 协议扩展与关联类型:用 protocol JSONDecodable { associatedtype Model: Decodable } 把“如何找 T”抽象成策略。
  2. 类型擦除与泛型特化:容器使用 AnyDecodable<T> 擦除具体策略,避免把策略类型暴露到调用方。
  3. 自定义 CodingKey 与 nestedContainer:在容器层动态解析可变 key,再丢给 T 解码。
  4. 编译期派发 vs 运行时反射:Swift 不用反射,靠泛型特化生成专用解码路径,性能与类型安全兼得。
  5. 错误处理:区分 DecodingError.keyNotFound 与 typeMismatch,给出业务可读的 “path: codingPath” 日志,方便国内后端联调。
  6. SPM 模块化:把策略协议放 Module A,具体策略放 Module B,业务工程只依赖 A,符合国内“基础库下沉、业务库上浮”的仓库治理规范。

答案

核心思路:把“如何取到 T”做成策略协议,让泛型容器持有策略,编译期特化出专用解码路径。

// 1. 策略协议:任何能剥出 Model 的东西
public protocol JSONDecodable {
    associatedtype Model: Decodable
    static func extract(from decoder: Decoder) throws -> Model
}

// 2. 泛型容器:只关心“我内部有一个 T”,不关心 JSON 长啥样
public struct ResponseBox<T: Decodable, Strategy: JSONDecodable> where Strategy.Model == T {
    public let value: T
}

extension ResponseBox: Decodable {
    public init(from decoder: Decoder) throws {
        value = try Strategy.extract(from: decoder)
    }
}

// 3. 两种常见策略(可继续扩展)
public enum StandardDataStrategy<T: Decodable>: JSONDecodable {
    public static func extract(from decoder: Decoder) throws -> T {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        return try container.decode(T.self, forKey: .data)
    }
    private enum CodingKeys: String, CodingKey { case data }
}

public enum ResultStrategy<T: Decodable>: JSONDecodable {
    public static func extract(from decoder: Decoder) throws -> T {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        return try container.decode(T.self, forKey: .result)
    }
    private enum CodingKeys: String, CodingKey { case result }
}

// 4. 业务方调用:一行代码,编译期决定策略
struct User: Decodable { let name: String }

let json1 = #"{"code":0,"data":{"name":"zhangsan"}}"#.data(using: .utf8)!
let user = try JSONDecoder().decode(ResponseBox<User, StandardDataStrategy<User>>.self, from: json1).value

let json2 = #"{"status":"ok","result":{"name":"lisi"}}"#.data(using: .utf8)!
let user2 = try JSONDecoder().decode(ResponseBox<User, ResultStrategy<User>>.self, from: json2).value

亮点:

  • 新增接口只需写一个新的 JSONDecodable 实现,零侵入旧代码;
  • 所有策略都是值类型,无运行时注册、无反射,符合 Swift 性能模型;
  • 错误信息携带完整 codingPath,国内后端联调时可直接定位字段。

拓展思考

  1. 如果后端返回的是数组根节点 [T],如何不改容器就让 ResponseBox<[T], Strategy> 继续工作?
    提示:给 Strategy 增加一个 associatedtype Input = T 与 static func extractArray,在容器里用 Strategy.Input == [T] 做条件编译。
  2. 当 JSON 里出现动态 key(如字典 ["10086": User]),而业务方只想拿 User,如何在不写 AnyDecodable 的前提下,让策略协议仍然返回 T?
    提示:用 decoder.singleValueContainer().decode([String: T].self).values.first 在策略层解决,容器层保持透明。
  3. 国内大厂常见“加密 + 压缩”场景:先 base64 解码、再 gzip 解压,最后才是 JSON。如何把“解密”也纳入策略,使网络层仍然只暴露 ResponseBox<T, Strategy>?
    提示:把策略协议拆成两阶段 Preprocess & JSONDecodable,在容器 init(from:) 里先 Preprocess.process(decoder) 拿到原始 Decoder,再交给 JSONDecodable.extract。
  4. 如果团队已经全面使用 Swift Concurrency,如何把上面的 JSONDecoder().decode 封装成 func request<T, S>(_ box: ResponseBox<T, S>.Type) async throws -> T 并集成到 URLSession.shared.data(from:) 的异步扩展里?
    提示:用 generic where S.Model == T 做泛型约束,避免重复声明 T。