JSONDecoder不解析数据

时间:2018-02-19 17:14:45

标签: ios json swift swift4 decodable

我正在尝试从此网址获取数据

https://api.opendota.com/api/heroStats

我做了struct

struct HeroStats : Decodable {
    let localized_name: String
    let primary_attr: String
    let attack_type: String
    let legs: Int
    let image: String
}

我的视图控制器顶部

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()
}

由于某种原因,我总是返回JSON ERROR,尽管一切似乎都是正确的。

1 个答案:

答案 0 :(得分:1)

尝试在Swift中的Codable / Encodable上阅读更多内容 Encoding and Decoding custom types

您可能希望通过使Swift名称与JSON名称不同来改进代码

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"
    }
}