【发布时间】: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:
【问题讨论】:
-
您是否尝试在
print(decoder)之前取消注释该行?而且打印解码器也没有意义。 -
唯一打印的是“Foundation.JSONDecoder”因为这是您要求打印的唯一内容。
-
我尝试取消注释:“线程 5:致命错误:Array
不符合 Decodable,因为 Artwork 不符合 Decodable” -
你能展示你的模型和预期的回报 json
-
我已经做到了。
标签: json swift jsondecoder