【问题标题】:JSON using Swift 4使用 Swift 4 的 JSON
【发布时间】:2018-02-10 16:46:51
【问题描述】:

首先,我的问题可能已经被问过了,但我在很多教程和论坛上搜索,但我无法解决问题,因为我是法国人,英语不太好。

我尝试使用我的应用程序读取 JSON,但它不起作用。唯一打印的是“Foundation.JSONDecoder”

这是我的 SWIFT 4 代码:

func getSpots(){
    guard let downloadURL = URL(string: "http://dronespot.fr/getSpot.php") else { return }
    URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
        guard let data = data, error == nil, urlResponse != nil else {
            print("Oops Call for Help")
            return
        }

        print("downloaded")
        do
        {
            let decoder = JSONDecoder()
            //let rates = try decoder.decode([Artwork].self, from: data)
            print(decoder)
        } catch {
            print("Error after loading")
        }
        }.resume()
}

Artwork.swift:

init?(json: [Any]) {
    // 1
    self.title = json[16] as? String ?? "No Title"
    self.locationName = json[12] as! String
    self.id = 3
    self.img = "tamere"
    // 2
    if let latitude = Double(json[18] as! String),
        let longitude = Double(json[19] as! String) {
        self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    } else {
        self.coordinate = CLLocationCoordinate2D()
    }
}

预期的 JSON:

http://dronespot.fr/getSpot.php 感谢您的帮助

【问题讨论】:

  • 您是否尝试在 print(decoder) 之前取消注释该行?而且打印解码器也没有意义。
  • 唯一打印的是“Foundation.JSONDecoder”因为这是您要求打印的唯一内容。
  • 我尝试取消注释:“线程 5:致命错误:Array 不符合 Decodable,因为 Artwork 不符合 Decodable”
  • 你能展示你的模型和预期的回报 json
  • 我已经做到了。

标签: json swift jsondecoder


【解决方案1】:

由于您想使用JSONDecoder,因此您的方法完全错误(除了您注释掉解码 JSON 的实际行的问题)。

创建Artwork为采用Decodable的结构体,将JSON中的键声明为属性,并添加惰性实例化变量来构建坐标:

struct Artwork : Decodable {
    let nom : String
    let description : String
    let id: String
    let img1 : String
    let latitude : String
    let longitude : String

    // there are much more keys

    lazy var coordinate : CLLocationCoordinate2D = {
        return CLLocationCoordinate2D(latitude: Double(latitude) ?? 0.0, longitude: Double(longitude) ?? 0.0)
    }()
}

现在解码Artwork的数组

do {
    let decoder = JSONDecoder()
    let rates = try decoder.decode([Artwork].self, from: data)
    print(rates)
} catch {
    print("Error after loading", error)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2019-01-02
    相关资源
    最近更新 更多