首页 > 解决方案 > 我收到错误 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()

标签: iosjsonswifttype-mismatch

解决方案


错误信息在这里很清楚。这意味着 Response 结构中使用的变量“code”被声明为 Int,但它在 JSON 响应中的类型是 String。


推荐阅读