gpt4 book ai didi

ios - Swift 4 Decodable 解析数组中的 json 数据

转载 作者:行者123 更新时间:2023-11-30 11:18:33 25 4
gpt4 key购买 nike

我在解析来自 Web 服务的数据时遇到问题,可解码协议(protocol)似乎无法解析此 json data

这是我使用泛型解析数据。

public func requestGenericData<T: Decodable>(urlString: String, httpMethod: String?, token: String!, completion: @escaping(T) ->()) {
let fullStringUrl = url + urlString
guard let url = URL(string: fullStringUrl) else { return }
guard let token = token else { return }
var urlRequest = URLRequest(url: url)
urlRequest.setValue("application/json", forHTTPHeaderField: "accept")
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
urlRequest.httpMethod = httpMethod
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if self.isInternetAvailable() {
guard let data = data else { return }
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 {
do {
let obj = try JSONDecoder().decode(T.self, from: data)
completion(obj)
} catch {
print("Error: \(String(describing: error))\n StatusCode: \(httpResponse.statusCode)")
}
}
}
} else {
showAlert(title: "No Internet Connect", message: "Please open your network and try again.", alertStyle: .alert, buttonTitle: "OK", buttonStyle: .default)
return
}
}.resume()
}

这是我的模型

struct JobWithCategory: Decodable {
let jobTypeID: Int
let jobCategoryID: Int
let name: String
let getJobs: [getJobs]
}
struct getJobs: Decodable {
let name: String
let description: String
}
struct JobCategories: Decodable {
let jobCategories: [JobWithCategory]
}


apiHelper.requestGenericData(urlString: "url/on/something/else", httpMethod: "GET", token: token) { (jobCategories: [JobCategories]) in
print(jobCategories)
}

现在我在控制台上打印了这个问题:

Error: typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

我的实现过程中遗漏了什么或出了什么问题吗?有人可以帮我解决这个问题吗?请详细说明为什么会发生这种情况,以便我可以很好地了解代码中发生的情况。

提前致谢:)

最佳答案

请阅读错误消息

Expected to decode Array but found a dictionary instead

预期一侧显示您正在做什么(错误),发现一侧显示实际类型。

可解码而言,字典是一个结构。所以是这样的

...{ (jobCategories: JobCategories) in

关于ios - Swift 4 Decodable 解析数组中的 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51538210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com