2017-02-14 116 views
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 

任何思考如何解決這個問題,爲什麼出現這種情況?

+0

被解析JSON對象是字典的陣列。嘗試打印'print(json.first?[「name」])' – vfn

+0

@vfn從'print(json.first?[「name」])得到錯誤' 'JSON._Element'(aka'(String ,JSON)')具有無標構件 – Pavlos

+0

這裏是解決方案: '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

回答

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" 
} 
相關問題