从 URL 解析 JSON 最终出现错误 - Swift 5

2024-05-29

我正在尝试用 swift 编写一个函数,从 URL JSON 获取数据,并将其分配给 swift 中的变量。

这是函数:

func getBikeData(){
    guard let url = URL(string: "https://api.citybik.es//v2/networks/baksi-bisim") else {return}
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let dataResponse = data,
              error == nil else {
              print(error?.localizedDescription ?? "Response Error")
              return }
        do{
            //here dataResponse received from a network request
            let jsonResponse = try JSONSerialization.jsonObject(with:
                                   dataResponse, options: [])
            print(jsonResponse) //Response result


            do {
                //here dataResponse received from a network request
                let decoder = JSONDecoder()
                //Decode JSON Response Data

                let model = try decoder.decode(Station.self,
                                               from: dataResponse)
                print(model.freeBikes) //Output - 1221

            } catch let parsingError {
                print("Error", parsingError)
            }
         } catch let parsingError {
            print("Error", parsingError)

       }
    }
    task.resume()

}

这是我添加的结构以及我需要的数据:

    // MARK: - Station
struct Station: Codable {
    let emptySlots: Int
    let extra: Extra
    let freeBikes: Int
    let id: String
    let latitude, longitude: Double
    let name, timestamp: String

    enum CodingKeys: String, CodingKey {
        case emptySlots
        case extra
        case freeBikes
        case id, latitude, longitude, name, timestamp
    }
}

// MARK: - Extra
struct Extra: Codable {
    let slots: Int
    let status: Status
    let uid: String
}

enum Status: String, Codable {
    case active = "Active"
}

这是我收到的错误:

Error keyNotFound(CodingKeys(stringValue: "emptySlots", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"emptySlots\", intValue: nil) (\"emptySlots\").", underlyingError: nil))

这是我第一次使用 JSON 文件,也许我遗漏了一些非常简单的东西。请帮忙。


以下是将所有 json 数据解码为 swift 结构的方法:

import Foundation


struct Stations: Codable {
    let company: [String]
    let href: String
    let id: String
    let location: LocationJson
    let name: String
    let stations: [Station]

}


struct Station: Codable {
    let empty_slots: Int
    let extra: Extra
    let free_bikes: Int
    let id: String
    let latitude: Double
    let longitude: Double
    let name: String
    let timestamp: String

}

struct ResponseJSON: Codable {
    let network: Stations
}

struct LocationJson: Codable {
    let city: String
    let country: String
    let latitude: Double
    let longitude: Double
}


struct Extra: Codable {
    let slots: Int
    let status: String
    let uid: String
}


func getBikeData(){
    guard let url = URL(
        string: "https://api.citybik.es//v2/networks/baksi-bisim"
    ) else { return }

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let dataResponse = data, error == nil else {
            print(error?.localizedDescription ?? "Response Error")
            return
        }
        do {
            //here dataResponse received from a network request
            let jsonResponse = try JSONSerialization.jsonObject(with:
                                   dataResponse, options: [])
            print(jsonResponse) //Response result


            do {
                //here dataResponse received from a network request
                let decoder = JSONDecoder()
                //Decode JSON Response Data

                let model = try decoder.decode(
                    ResponseJSON.self, from: dataResponse
                )
                print(model) //Output - 1221

            } catch let parsingError {
                print("Error", parsingError)
            }

         } catch let parsingError {
            print("Error", parsingError)
         }
    }
    task.resume()

}

getBikeData()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 URL 解析 JSON 最终出现错误 - Swift 5 的相关文章

随机推荐