ios - 我收到错误 Expected to decode Int 但在 swift 上找到了一个字符串/数据
问题描述
我不知道为什么我会收到这个错误。控制台说我将代码声明为字符串,但它实际上是一个 Int。有什么帮助吗?
我得到的确切错误消息是这个:
DEBUG: Something happened and couldn't fetch the data: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "code", intValue: nil)], debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil))))
DEBUG: There was an error with the API calling: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "code", intValue: nil)], debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil))))
我的结构:
struct Response: Decodable {
let code: Int?
let status: String?
let copyright: String?
var data: MarvelData?
}
编辑1:我的其余结构。
struct MarvelData: Decodable {
let count: Int?
var limit: Int?
let offset: Int?
let results: [Characters]?
}
struct Characters: Decodable {
var id: Int?
var name: String?
var description: String?
var thumbnail: Images?
}
JSON Schema 是: JSON Schema
我的 API 调用是:
AF.request(baseURL, parameters: ["apikey": publicKey,
"ts" : ts,
"hash": hash]).responseMarvel { (response) in
if let error = response.error {
print("DEBUG: Something happened and couldn't fetch the data: \(error)")
handler(.failure(error))
}
do {
let marvelFetch = response.value
let results = marvelFetch?.data?.results
guard let marvelStuff = results as [Characters]? else { return }
characterArray = marvelStuff
handler(.success(characterArray))
} catch {
print("DEBUG: You had an error creating JSON: \(error)")
}
}.resume()
解决方案
错误信息在这里很清楚。这意味着 Response 结构中使用的变量“code”被声明为 Int,但它在 JSON 响应中的类型是 String。
推荐阅读
- c - 指向 char 和 printf 的指针
- python - 在 ubuntu 18.04 中安装系统范围的模块
- java - 当tomcat从tomcat 7升级到tomcat 9时,Drools ClassCastException
- java - 通过特定路由将 Java 客户端连接到 Node Express 服务器
- session - 带有用户信息的 Kong API 网关会话插件
- firebase - 解决 PlatformException (PlatformException(user-not-found)) Firebase
- yaml - Github 页面仅显示前端
- mysql - 为什么当我使用 MYSQL INSERT 语句时 CURTIME()) 有效但 NOW() 无效?
- php - 注意未定义的偏移量:2
- javascript - 根据购物车总数计算进度条状态