gpt4 book ai didi

json - swift : The data couldn’t be read because it isn’t in the correct format

转载 作者:行者123 更新时间:2023-12-04 12:18:57 27 4
gpt4 key购买 nike

我尝试使用 Alamofire 调用 POST Api,但它向我显示格式不正确的错误。

这是我的 JSON 响应:

[
{
"_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 进行解码的方式。
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相关代码,那部分很好。

显着改进:
  • 通过自定义 CodingKeys 避免了模型中的下划线变量名用于键映射目的
  • 类型名称应始终以大写字母开头(因此 _sourceSource )
  • 同样,变量名应始终以小写字母
  • 开头。
  • 将一些变量设为可选(基于您更新的响应)
  • 保持变量非可选意味着它 必须出现在要创建的模型的响应中
  • 将变量设为可选意味着 key 可能存在也可能不存在于响应中,并且不存在不会阻止创建模型
  • 关于json - swift : The data couldn’t be read because it isn’t in the correct format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55030573/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com