【问题标题】:Swift The data couldn’t be read because it isn’t in the correct formatSwift 无法读取数据,因为它的格式不正确
【发布时间】:2021-05-25 21:28:28
【问题描述】:

我是 swift 新手,正在尝试弄清楚如何将 JSON 解析为结构。我正在尝试从 NASA Mar 的漫游者照片中获取图像。我正在尝试在线学习教程,但似乎无法解决此问题。我在这里做错了什么?

错误:

致命错误:由于格式不正确,无法读取数据。

import Foundation

class API {
    class func getImage(_ onSucessus: @escaping ([LatestPhoto]) -> ()){
        Constrant.session.dataTask(with: Constrant.request){(data, res, err) in
            guard let data = data, err == nil else{
                fatalError()
            }
            do{
                let apod = try Constrant.decoder.decode([LatestPhoto].self, from: data)
                DispatchQueue.main.async {
                    onSucessus(apod)
                }
            }
            catch{
                fatalError(error.localizedDescription)
            }
            
        }.resume()
        
    }
}

结构

struct LatestPhoto: Identifiable, Codable{
    let id = UUID()
    let imgSrc: String
    let earthDate: String

    enum CodingKeys: String, CodingKey {
        case imgSrc = "img_src"
        case earthDate = "earth_date"
      
    }
}

JSON

{
  "latest_photos": [
    {
      "id": 839114,
      "sol": 3127,
      "camera": {
        "id": 20,
        "name": "FHAZ",
        "rover_id": 5,
        "full_name": "Front Hazard Avoidance Camera"
      },
      "img_src": "https://mars.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/03127/opgs/edr/fcam/FRB_675093431EDR_F0880366FHAZ00302M_.JPG",
      "earth_date": "2021-05-23",
      "rover": {
        "id": 5,
        "name": "Curiosity",
        "landing_date": "2012-08-06",
        "launch_date": "2011-11-26",
        "status": "active"
      }
    },
    {
      "id": 839115,
      "sol": 3127,
      "camera": {
        "id": 20,
        "name": "FHAZ",
        "rover_id": 5,
        "full_name": "Front Hazard Avoidance Camera"
      },
      "img_src": "https://mars.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/03127/opgs/edr/fcam/FLB_675093431EDR_F0880366FHAZ00302M_.JPG",
      "earth_date": "2021-05-23",
      "rover": {
        "id": 5,
        "name": "Curiosity",
        "landing_date": "2012-08-06",
        "launch_date": "2011-11-26",
        "status": "active"
      }
    }
  ]
}

【问题讨论】:

    标签: json swift


    【解决方案1】:

    您的 JSON 格式与您尝试解码的格式不完全匹配。您需要一个用于 JSON 对象根目录的 latest_photos 数组的包装器。

    例如:

    struct LatestPhotosWrapper: Codable {
        let latestPhotos: [LatestPhoto]
        
        enum CodingKeys: String, CodingKey {
            case latestPhotos = "latest_photos"
        }
    }
    
    let apod = try JSONDecoder().decode(LatestPhotosWrapper.self, from: data)
    

    (除了提供CodingKey,您还可以查看用于从蛇盒转换的内置系统:https://developer.apple.com/documentation/foundation/jsondecoder/keydecodingstrategy/convertfromsnakecase

    此外,您可能想要打印error 而不仅仅是error.localizedDescription——您可以更好地了解正在发生的事情。例如,使用您的原始代码,您会得到:

    本应解码 Array 但找到了字典。

    最后,您可以查看 app.quicktype.io - 您可以粘贴 JSON 并为您预先构建正确的 Swift 结构。

    【讨论】:

    • 现在可以使用了。非常感谢您的帮助。
    猜你喜欢
    • 2019-07-28
    • 2021-11-11
    • 1970-01-01
    • 2017-06-12
    • 2018-12-25
    • 2020-03-11
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多