0
我導入了Alamofire和SwiftyJSON(最新版本),我只想嘗試API調用。使用Alamofire和SwiftyJSON,當我使用json [「email」]時它返回空值?
這裏我在做什麼在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
任何思考如何解決這個問題,爲什麼出現這種情況?
被解析JSON對象是字典的陣列。嘗試打印'print(json.first?[「name」])' – vfn
@vfn從'print(json.first?[「name」])得到錯誤' 'JSON._Element'(aka'(String ,JSON)')具有無標構件 – Pavlos
這裏是解決方案: 'Alamofire.request(URL,方法:。獲得) .validate() .responseJSON {在 開關response.result { 情況.success響應: //從大小寫中除去值.success(let value): let json = JSON(data:response.data!) if let name = json [0] [「name」]。string { //現在你得到了你的價值 print(name) } case .failure(let error): print(error) } }' – Pavlos