从 api 解码数据时在 swift 中出现错误

问题描述

错误:- 解码时出错 typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath: [],debugDescription: "Expected to decode Array but found adictionary instead.",underlyingError: nil))

#Fetch 函数

static func fetchEmployeeDetail(id:Int,apiURL: String,completion: @escaping(Result<[Users],Error>) -> Void) {
        print(id,apiURL)
        
        let resourceString = "\(stringURL)\(id)\(apiURL)"
        print(resourceString)
        guard let resourceURL = URL(string: resourceString) else {fatalError()}

        let dataTask = URLSession.shared.dataTask(with: resourceURL) {data,_,_ in
            guard let jsonData = data else {
                print(errno)
                return
            }
            
            do {

                let userResponse = try JSONDecoder().decode([Users].self,from: jsonData)
                completion(.success(userResponse))
                print(userResponse)
            }catch{
                print("Error while decoding \(error)")
                if let data = data,let dataString = String(data: data,encoding: .utf8){
                    print(dataString)
                }
            }

        }

        dataTask.resume()
        
        
    }

#模型

struct Users: Codable {
    var id: Int
    var sr_no: Int
    var first_name: String
    var last_name: String
    var email: String

    init(id: Int,sr_no:Int,first_name: String,las_name: String,email: String) {
        self.id = id
        self.sr_no = sr_no
        self.first_name = first_name
        self.last_name = las_name
        self.email = email
    }
}

印刷

2 / http://192.168.27.165:8000/employees/2/ 解码 typeMismatch(Swift.Array,debugDescription: "Expected to decode Array but found a dictionary.",underlyingError: nil)) 时出错 {"id":2,"sr_no":2,"first_name":"Karan","last_name":"Sach Deva","email":"karan@gftpl.in"}

解决方法

您需要 Users.self 而不是 [Users].self

let userResponse = try JSONDecoder().decode(Users.self,from: jsonData)

改变

@escaping(Result<Users,Error>) -> Void) { print(id,apiURL)