[英]JSONDecoder Not Parsing Data
I am trying to get data from this URL我正在尝试从此 URL 获取数据
https://api.opendota.com/api/heroStats
I have made a struct
我做了一个
struct
struct HeroStats : Decodable {
let localized_name: String
let primary_attr: String
let attack_type: String
let legs: Int
let image: String
}
Top of my View Controller我的视图控制器的顶部
var heros = [HeroStats]()
func downloadJSON(completed: @escaping () -> ()) {
let url = URL(string: "https://api.opendota.com/api/heroStats")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error.debugDescription)
}
do {
guard let data = data else { return}
self.heros = try JSONDecoder().decode([HeroStats].self, from: data)
DispatchQueue.main.async {
completed()
}
print(self.heros)
} catch {
print("JSON ERROR")
return
}
}.resume()
}
I always return JSON ERROR for some reason, although everything seems to be correct.我总是出于某种原因返回 JSON ERROR,尽管一切似乎都是正确的。
Try to read more on Codable
/ Encodable
in Swift Encoding and Decoding custom types尝试阅读更多关于
Codable
/ Encodable
in Swift Encoding and Decoding custom types
You may want to improve your code by making Swift names that differs from JSON names您可能希望通过创建与 JSON 名称不同的 Swift 名称来改进您的代码
struct HeroStats: Codable {
let name: String
let primaryAttribute: String
let attackType: String // Better to be an enum also
let legs: Int
let image: String?
enum CodingKeys: String, CodingKey {
case name = "localized_name"
case primaryAttribute = "primary_attr"
case attackType = "attack_type"
case legs
case image = "img"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.