JSONDecoder 不解析数据

Posted

技术标签:

【中文标题】JSONDecoder 不解析数据【英文标题】:JSONDecoder Not Parsing Data 【发布时间】:2018-02-19 17:14:45 【问题描述】:

我正在尝试从此 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,尽管一切似乎都是正确的。

【问题讨论】:

不要只打印字符串“JSON ERROR”,打印实际错误(print(error)),这样您就可以看到错误是什么 API 响应中是“img”而不是图像 数据丢失,无法读取。 - 描述 @user9335240 谢谢它的工作原理!澄清..即使结构字段之一是错误的,为什么不跳过它并填写其他字段? 如果您不将该字段标记为可选,如果它不存在则会引发错误 【参考方案1】:

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

您可能希望通过使用不同于 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"
    

【讨论】:

以上是关于JSONDecoder 不解析数据的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 JSONDecoder 根据订单键获取排序数据?

如何在 iOS 中解析没有 JSONdecoder 的 JSON 对象? [复制]

为啥 JsonDecoder 在尝试解析邮递员网址但处理其他网址时出现错误?

Swift - 使用 JSONDecoder 解码 JSON 数据

告诉 numberOfRowsInSection 在使用 MVVM 架构在闭包中使用 JSONDecoder 解析 JSON 后它需要多少行

JSONDecoder 找不到存在的密钥