json - Api 调用返回错误 **keyNotFound....**
问题描述
我正在尝试进行 api 调用,我正在查询中构建 api 并像往常一样解析它,但我收到错误:
keyNotFound(CodingKeys(stringValue: "locationType", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue :“locationType”,intValue:nil)(“locationType”)。”,基础错误:nil) **)
获取数据:
func fetchData(completionHandler: @escaping ([Root]) -> Void) {
let queryItems = [URLQueryItem(name: "lat", value: "51.176519"),URLQueryItem(name: "lng", value: "-0.622557"),URLQueryItem(name: "date", value: "2020-11")]
var urlComponents = URLComponents(string: "https://data.police.uk/api/crimes-street/all-crime")
urlComponents?.queryItems = queryItems
guard let combinedUrl = urlComponents?.url else {return}
print(combinedUrl)
let task = URLSession.shared.dataTask(with: combinedUrl,completionHandler : { (data, response, error) in
if let error = error {
print("Error with fetching accounts: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...400).contains(httpResponse.statusCode) else {
print("Error with the response , unexpected status code:\(response)")
return
}
guard let data = data else {return}
do {
let decoder = JSONDecoder()
let dataSummary = try decoder.decode([Root].self, from: data)
completionHandler(dataSummary.self ?? [])
} catch {
print(error)
}
})
task.resume()
}
视图控制器:
override func viewDidLoad() {
super.viewDidLoad()
networking.fetchData{[weak self] (jsonValues) in
self?.jsonValues = jsonValues ;print("JSON values Inside closure : \(jsonValues)")
}
print("JSON values outside closure: \(jsonValues)")
}
根结构:
public struct Root: Codable {
public let category, location_Type: String
public let location: Location
public let context: String
public let outcomeStatus: OutcomeStatus
public let persistentId: String
public let id: Int
public let locationSubtype, month: String
public init(category: String, locationType: String, location: Location, context: String, outcomeStatus: OutcomeStatus, persistentId: String, id: Int, locationSubtype: String, month: String) {
self.category = category
self.locationType = locationType
self.location = location
self.context = context
self.outcomeStatus = outcomeStatus
self.persistentId = persistentId
self.id = id
self.locationSubtype = locationSubtype
self.month = month
}
}
任何帮助都会很棒!
解决方案
该错误表明它在 API 响应中找到 nil ,因为我没有考虑到响应可以是nil我在Root struct 中设置了可选值,然后它成功解析。
public let category, location_Type: String?
public let location: Location
public let context: String
public let outcomeStatus: OutcomeStatus?
public let persistentId: String?
public let id: Int
public let locationSubtype, month: String?
推荐阅读
- angular - SAP Spartacus - 如何在插槽中围绕 2 个自定义组件包装元素?
- javascript - 像按钮影响所有视频的问题
- html - 使用变量更改带有样式组件的 React 项目的 CSS 属性
- python - vs-code python 调试当前文件 SimpleHTTPRequestHandler
- python - 使用 pyQgis 导出 sld
- r - r 将数据帧拆分并导出到 word/powerpoint
- palantir-foundry - 在 Foundry Scenarios 中,是否可以跨多个场景运行函数?
- javascript - 将 JavaScript 字符串格式转换为另一种
- c# - .NET Core 和 C#:如果没有 webHost.Run,IHostedServices 不会自动运行
- sql - 使用 VBA 更新和现有 OLEDB 连接