2016-09-30 60 views
0

我的代碼是這個類型任何沒有下標構件迅速3

import UIKit 
import Alamofire 

class ViewController: UIViewController { 


var young = "https://jsonplaceholder.typicode.com/posts" 


override func viewDidLoad() { 
    super.viewDidLoad() 

    callAlamo(url: young) 
} 

func callAlamo(url: String){ 

    Alamofire.request(url).responseJSON { (response) in 
     let responseJSON = response.data 
     if responseJSON == nil{ 
      print("response is empty") 
     }else{ 
      print("Jon is \(responseJSON)") 

      self.parseJson(JSONData: responseJSON!) 
     } 

    } 
} 

func parseJson(JSONData: Data){ 

    do{ 
     let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) 

     for i in 0..<(readableJSON as AnyObject).count{ 
      print(readableJSON[i] as String) 
     } 

    }catch{ 
     print(error) 
    } 
} 
} 

enter image description here

我需要此JSON內的每個數組元素。

+3

有關於非常相同的錯誤信息>> 20個問題。請檢查您的問題是否未被回答。 –

+1

你能告訴我你的JSON,你正在獲得表單服務嗎? –

回答

3

嘗試使用下面的代碼:

Alamofire.request(url).responseJSON { (response) in 

     switch response.result { 
     case .success(let value) : 

      print(response.request) // original URL request 
      print(response.response) // HTTP URL response 
      print(response.data)  // server data 
      print(response.result) // result of response serialization 

      if let JSON = response.result.value as! [String:AnyObject]!{ 
       print("JSON: ",JSON) 
      } 
     case .failure(let encodingError): 
      completionHandler(APIResponse.init(status: "failure", response: nil, result:nil)) 
     } 
    } 
0

當使用responseJSON處理程序,該JSON數據已經被內部由JSONSerialization解析。你做不是想嘗試再次解析它,否則你解析服務器的響應數據兩次,這是非常糟糕的性能。所有你需要做的是以下幾點:

Alamofire.request(url).responseJSON { response in 
    if let json = response.result.value { 
     print("Parsed JSON: \(json)") 
     // Now you can cast `json` to a Dictionary or Array 
    } 
}