【发布时间】:2019-07-28 13:25:30
【问题描述】:
我尝试使用 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)
}
}
}
【问题讨论】:
-
从不在解码 JSON 时打印
error.localizedDescription。打印error,它会告诉你到底出了什么问题。并停止使用那些丑陋的 objective-c-ish 下划线字符。 Swift 中的结构以大写字母开头!
标签: json swift alamofire jsondecoder