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 } }
关键调整说明:
- 新增AnyHashable处理分支:递归解析
AnyHashable包装的原始值,覆盖Apollo内部可能的包装逻辑 - 补充数组类型处理:避免接口返回数组时同样触发解码错误
- 替换fallthrough为明确错误抛出:原代码的
fallthrough会直接走default分支,改为针对当前类型抛出错误,便于调试定位 - 优化jsonValue实现:确保编码时能将字符串转回对应的JSON对象(如果接口期望接收原始字典/数组类型,这个调整是必要的)
内容的提问来源于stack exchange,提问作者Paresh Patel
相关产品推荐
相关产品推荐

