2016-09-30 64 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 
    } 
}