-1

我正在尝试从此 URL 获取数据

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,尽管一切似乎都是正确的。

4

1 回答 1

1

Try to read more on 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

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"
    }
}
于 2018-02-19T17:23:51.987 回答