Json Api调用返回错误**keyNotFound**

Json Api调用返回错误**keyNotFound**,json,swift,xcode,api,swift5,Json,Swift,Xcode,Api,Swift5,我正在尝试进行api调用,我正在查询中构建api并像往常一样对其进行解析,但我遇到了错误: keyNotFound(编码键(stringValue:“locationType”,intValue:nil),Swift.DecodingError.Context(编码路径:[[u JSONKey(stringValue:“索引0”,intValue:0)],调试说明:“没有与键编码键相关联的值(stringValue:“locationType”,intValue:nil)(“locationTy

我正在尝试进行api调用,我正在查询中构建api并像往常一样对其进行解析,但我遇到了错误:

keyNotFound(编码键(stringValue:“locationType”,intValue:nil),Swift.DecodingError.Context(编码路径:[[u JSONKey(stringValue:“索引0”,intValue:0)],调试说明:“没有与键编码键相关联的值(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,我在根结构中设置了可选值,然后它成功解析

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?

print(jsonValues)
替换为
print(“闭包外的JSON值:\(jsonValues)”)
,并将
self?.jsonValues=jsonValues
替换为
self?.jsonValues=jsonValues;打印(“闭包内的JSON值::\(self?.jsonValues)”)
,请先查看打印的内容?嘿,感谢您的评论,我已经替换了您推荐的内容。“”重写func viewdiload(){super.viewdiload()networking.fetchData{[weak self](jsonValues)in self?.jsonValues=jsonValues;print(“闭包内的JSON值:(jsonValues)”)}''print(“闭包外的JSON值:(jsonValues)”)}它唯一要打印的是闭包外的JSON,闭包是空的[]现在,执行适当的
do{try}catch{}
而不是
try?
并打印错误。您当前只是忽略了错误。因此我添加了do catch block
do{let decoder=JSONDecoder()let dataSummary=try decoder.decode([Root].self,from:data)completionHandler(dataSummary.self???[])catch{print(error.localizedDescription)}
错误是数据丢失,无法读取。不确定出了什么问题。不要打印本地化描述,只打印错误。