You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GraphQL 1.9.3(iOS Swift)自定义标量JSON解码问题求助

解决Apollo GraphQL 1.9.3中JSON自定义标量的解码错误

你遇到的ApolloAPI.JSONDecodingError.couldNotConvert(value: AnyHashable to: Swift.String)错误,核心原因是接口返回的值被包装成了AnyHashable类型,但你的JSON扩展没有处理这种情况,直接走到了default分支抛出错误。下面是调整后的代码方案:

extension JSON: JSONDecodable, JSONEncodable {
    public init(jsonValue value: JSONValue) throws {
        switch value {
        case let string as String:
            self = string
        case let int as Int:
            self = String(int)
        case let dictionary as [String: Any]:
            guard let data = try? JSONSerialization.data(withJSONObject: dictionary, options: []) else {
                throw JSONDecodingError.couldNotConvert(value: dictionary, to: String.self)
            }
            guard let serializedJson = String(data: data, encoding: .utf8) else {
                throw JSONDecodingError.couldNotConvert(value: dictionary, to: String.self)
            }
            self = serializedJson
        case let array as [Any]:
            guard let data = try? JSONSerialization.data(withJSONObject: array, options: []) else {
                throw JSONDecodingError.couldNotConvert(value: array, to: String.self)
            }
            guard let serializedJson = String(data: data, encoding: .utf8) else {
                throw JSONDecodingError.couldNotConvert(value: array, to: String.self)
            }
            self = serializedJson
        // 新增处理AnyHashable包装值的分支
        case let hashable as AnyHashable:
            try self.init(jsonValue: hashable.base)
        default:
            throw JSONDecodingError.couldNotConvert(value: value, to: String.self)
        }
    }
    
    public var jsonValue: JSONValue {
        // 编码时将字符串转回原始JSON对象,适配接口期望的类型
        guard let data = self.data(using: .utf8),
              let jsonObject = try? JSONSerialization.jsonObject(with: data) else {
            return self
        }
        return jsonObject
    }
}

关键调整说明:

  1. 新增AnyHashable处理分支:递归解析AnyHashable包装的原始值,覆盖Apollo内部可能的包装逻辑
  2. 补充数组类型处理:避免接口返回数组时同样触发解码错误
  3. 替换fallthrough为明确错误抛出:原代码的fallthrough会直接走default分支,改为针对当前类型抛出错误,便于调试定位
  4. 优化jsonValue实现:确保编码时能将字符串转回对应的JSON对象(如果接口期望接收原始字典/数组类型,这个调整是必要的)

内容的提问来源于stack exchange,提问作者Paresh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:02:15