且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift:由于格式不正确,无法读取数据

更新时间:2021-08-23 00:28:20

只是您的Album模型不正确.

struct Album: Codable {
    var source : Source
    var id     : String

    enum CodingKeys: String, CodingKey {
        case source = "_source"
        case id = "_id"
    }
}

struct Source: Codable {
    var nome     : String
    var endereco : String?
    var uf       : String?
    var cidade   : String?
    var bairro   : String?
}

如果您不希望完全使用_id,则只需删除相关部分.
至于与Alamofire相关的代码,那部分很好.

If you don't want _id altogether then simply remove the related parts.
As for your Alamofire related code, that part is good.

显着改进:

  • 通过自定义CodingKeys以实现键映射目的,避免了模型中带下划线的变量名
  • 类型名称应始终以大写字母开头(因此_sourceSource)
    • 类似地,变量名应始终以小写字母开头
    • Have avoided underscored variable name in model by customizing CodingKeys for key mapping purpose
    • Typenames should always start with a Capital letter (so _source is Source)
      • Similarly, variable names should always start with a lowercase letter
      • 保留变量为非可选变量意味着它必须出现在要创建的模型的响应中
      • 将变量设为可选意味着响应中可能存在或可能不存在密钥,并且密钥不存在将不会阻止创建模型
      • Keeping a variable non-optional means it must be present in the response for the model to be created
      • Making a variable optional means that key may or may not be present in the response and it not being there won't prevent the model from being created