ios - 如何通过 Alamofire 和 SwiftyJSON 在 UIViewController 中使用根目录中的 JSON 对象

标签 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”,但无法访问 UIViewControllerUILabel 中的“Accept-Encoding”

我在编码中尝试的内容:

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]]     
    }
  }

我想在我的 UIViewControllerUILabel 中使用“标题”。

最佳答案

您正在尝试将 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
  }
}

关于ios - 如何通过 Alamofire 和 SwiftyJSON 在 UIViewController 中使用根目录中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46364652/

相关文章:

Swift - 从子类访问属性时遇到问题

ios - AVAudioPlayer 在使用调试脚本之前无法播放声音

ios - 在 Objective-C 中显示以编程方式放置在 Storyboard 放置的对象后面的对象

javascript - JSON 和 Object Literal Notation 有什么区别?

javascript - 无法从 json 字符串中删除双引号

php - 从 PHP INNER JOIN 表创建多维 JSON

ios - 过期后删除 TableView 行

ios - 带有自定义 init 的 UIView 不起作用

iOS Autolayout 调整标签大小和它们之间的空间

iphone - 在 Objective-C block 中调用 C 函数(链接器错误)