我导入了Alamofire和SwiftyJSON(最新版本),我只想尝试API调用。
这是我在viewDidLoad中所做的事情:
url: String = "https://api.solvap.com" //this is not the real url of the api
Alamofire.request(url, method: .get)
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
//this print statement prints the whole JSON list
print(json)
//this print statement just return null for some weird reason
print(json["name"])
case .failure(let error):
print(error)
}
}
Xcode中的控制台输出:
[
{
"name" : "John",
"surname" : "Doe",
"password" : "54321",
"job" : "Developer",
"token" : "iw4lcsk7h8do3y6fuw5vvzefn"
}
]
null
有任何想法如何解决这个问题以及为什么会发生这种情况?
答案 0 :(得分:0)
我想出来了..如果API响应如下:
(
{
"name" : "John",
"surname" : "Doe",
"password" : "54321",
"job" : "Developer",
"token" : "iw4lcsk7h8do3y6fuw5vvzefn"
}
)
这意味着API响应是错误的,完美的方法是修复来自后端的响应,而不是尝试从错误的API响应中解析数据。
没有理由浪费时间尝试从错误的API响应中解析数据。
API的正确响应应如下所示:
{
"name" : "John",
"surname" : "Doe",
"password" : "54321",
"job" : "Developer",
"token" : "iw4lcsk7h8do3y6fuw5vvzefn"
}