本文介绍了Swift:由于格式不正确,无法读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Alamofire调用POST Api,但它向我显示了格式错误的错误.

I try to call the POST Api with Alamofire but it's showing me an error of incorrect format.

这是我的JSON响应:

This is my JSON response:

[
  {
    "_source": {
      "nome": "LOTERIAS BELEM",
      "endereco": "R DO COMERCIO, 279",
      "uf": "AL",
      "cidade": "BELEM",
      "bairro": "CENTRO"
    },
    "_id": "010177175"
  },
  {
    "_source": {
      "nome": "Bel Loterias"
    },
    "_id": "80224903"
  },
  {
    "_source": {
      "nome": "BELLEZA LOTERIAS",
      "endereco": "R RIVADAVIA CORREA, 498",
      "uf": "RS",
      "cidade": "SANTANA DO LIVRAMENTO",
      "bairro": "CENTRO"
    },
    "_id": "180124986"
  }
]


class Album: Codable {
    var _source :  [_source]

}

class _source: Codable {
    var nome :  String
    var endereco : String
    var uf : String
    var cidade : String
    var bairro : String
}

var arrList = [Album]()

这就是我尝试使用Alamofire进行解码的方式.

And this is how i try to Decoding with Alamofire.

func request() {

        let urlString = URL(string: "My Url")
      //  Alamofire.request(url!).responseJSON {(response) in

        Alamofire.request(urlString!, method: .post, parameters: ["name": "belem"],encoding: JSONEncoding.default, headers: nil).responseJSON {
            (response) in

            switch (response.result) {
            case .success:
                if let data = response.data {
                    do {
                        let response = try JSONDecoder().decode([Album].self, from: data)
                        DispatchQueue.main.async {
                             self.arrList = response
                        }
                    }
                    catch {
                        print(error.localizedDescription)
                    }
                }
            case .failure( let error):
                print(error)
            }
       }
 }

推荐答案

只是您的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

      这篇关于Swift:由于格式不正确,无法读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:39