使用 Alamofire 和 SwiftyJSON,当我使用 json["email"] 时,它 returns 为空?
Using Alamofire and SwiftyJSON and it returns me null when I use json["email"]?
我导入了 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
知道如何解决这个问题以及为什么会发生这种情况吗?
我想通了。如果 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"
}
我导入了 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
知道如何解决这个问题以及为什么会发生这种情况吗?
我想通了。如果 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"
}