【发布时间】:2020-11-23 16:02:01
【问题描述】:
我无法弄清楚为什么会出现此错误。控制台说我将代码声明为字符串,但它实际上是一个 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 架构是: 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()
【问题讨论】:
-
失败的 JSON 是什么样子的?
-
在 JSON Schema 图片上
-
这意味着
code不是应有的Int。你打印了错误,但你也可以在catchprint("It failed with responseString "(String(data: response.data, encoding: .utf8) ?? "")")`中做 -
编辑您的问题并发布 API 返回的实际 JSON 字符串
-
@3rnestocs 上面的人的意思是,您能否向我们发送您用于
JSONDecoder().decode(Response.self, from: response.data)的原始 JSON 字符串。您可以在使用print(String(data: response.data, encoding: .utf8) ?? "No reponse")解码为实际模型之前完成此操作@
标签: ios json swift type-mismatch