Alamofire无法访问JSON响应的键

我新使用Alamofire并遇到问题。 我可以运行下面的代码来打印出API端点的所有数据。

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in if let JSON = response.result.value { print(JSON) } } 

问题是,当我运行这个:

 Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in if let JSON = response.result.value { print(JSON["firstkey"]) } } 

我得到的错误:

types“任何”没有下标成员

我不知道为什么这个错误发生,似乎我正确访问数据。 任何帮助将是伟大的,谢谢!

我已经尝试使用两种格式:

打印(JSON [“firstkey”]作为string)

打印(JSON [“firstkey”]为[String:Any]

但他们仍然给出同样的错误。

这是我的端点上的JSON:

 { "firstkey":"it worked!", "secondkey":["item1", "item2", "item3"] } 

这很简单。 你只需要强制施放(就像!)你的JSON。 所以改变你的代码,这将工作:

 Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in if let JSON = response.result.value { let json = JSON as! [String: Any] print(json["firstkey"]) } } 

编辑1:正如你在评论中说你正在使用SwiftyJSON包。 示例代码如下所示:

 Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in if let value = response.result.value { let json = JSON(value) print(json["firstkey"].stringValue) } } Alamofire.request("https://mmcalc.com/api").responseJSON { response in if let value = response.result.value { let json = JSON(value) print(json.arrayValue[0]["uniqueUsers"].stringValue) } } 

你正试图获得对象的价值,试试这个:

 Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in if let result = response.result.value { let JSON = result as! NSDictionary print(JSON["firstkey"]) } } 

希望它能工作!