如何在UIViewController中使用来自root的JSON对象与Alamofire和SwiftyJSON

时间:2017-09-22 12:18:17

标签: ios json swift alamofire

我想用Alamofire和SwiftyJSON解析JSON。

要解析的JSON:

{
  "args": {}, 
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", 
    "Accept-Encoding": "gzip, deflate", 
    "Accept-Language": "en-GB,en-US;q=0.8,en;q=0.6", 
    "Connection": "close", 
    "Cookie": "_gauges_unique_month=1; _gauges_unique_year=1; _gauges_unique=1", 
    "Host": "httpbin.org", 
    "Upgrade-Insecure-Requests": "1", 
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
  }, 
  "origin": "150.107.254.75", 
  "url": "http://httpbin.org/get"
}

我可以访问' args'但我无法访问“接受编码”#39;在我的UIViewController UILabel

我正在尝试编码:

let Endpoint: String = "http://httpbin.org/get"
  Alamofire.request(Endpoint).responseJSON { response in
    if let json = response.result.value as? Array<Dictionary<String,Any>> {
      self.arrRes = json as [[String:AnyObject]]     
    }
  }

我想使用&#39; Headers&#39;在我的UIViewController UILabel

1 个答案:

答案 0 :(得分:0)

你正在尝试将json转换为数组,但它是一个字典,试试这个:

let endpoint: String = "http://httpbin.org/get"
Alamofire.request(endpoint).responseJSON { response in
  if let json = response.result.value as? [String:Any],
     let headers = json["headers"] as? [String:Any] {

     self.label.text = headers["Accept-Encoding"] as? String
  }
}