我是使用Alamofire的新手,遇到了一个问题.我可以运行以下代码以打印出来自API端点的所有数据.
I'm new to using Alamofire and have encountered an issue. I'm able to run the following code to print out all the data from an API endpoint.
Alamofire.request("codewithchris/code/afsample.json").responseJSON { response in if let JSON = response.result.value { print(JSON) } }问题是,当我运行此命令时:
The issue is that when I run this:
Alamofire.request("codewithchris/code/afsample.json").responseJSON { response in if let JSON = response.result.value { print(JSON["firstkey"]) } }我得到了错误:
任何"类型没有下标成员
Type 'Any' has no subscript members
我不知道为什么会发生此错误,似乎我正在正确访问数据.任何帮助都会很棒,谢谢!
I don't know why this error is happening, it seems as if I'm accessing the data correctly. Any help would be great, thanks!
我尝试过同时使用以下两种格式:
I have tried formatting it using both:
print(JSON ["firstkey"]作为字符串)
print(JSON["firstkey"] as String)
和
print(JSON ["firstkey"] as [String:Any]
print(JSON["firstkey"] as [String:Any]
但是它们仍然给出相同的错误.
but they still give the same error.
这是我端点上的JSON:
This is the JSON on my endpoint:
{ "firstkey":"it worked!", "secondkey":["item1", "item2", "item3"] }推荐答案
这真的很简单.您只需要强制转换(如!)您的JSON.所以将您的代码更改为此,它将起作用:
This is really simple. You just need to force cast (as!) your JSON. so change your code to this and it will work:
Alamofire.request("codewithchris/code/afsample.json").responseJSON { response in if let JSON = response.result.value { let json = JSON as! [String: Any] print(json["firstkey"]) } }正如您在评论中所说,您正在使用SwiftyJSON包.示例代码如下:
Edit 1: As you said in comments that you are using SwiftyJSON package. Sample code is as follows:
Alamofire.request("codewithchris/code/afsample.json").responseJSON { response in if let value = response.result.value { let json = JSON(value) print(json["firstkey"].stringValue) } } Alamofire.request("mmcalc/api").responseJSON { response in if let value = response.result.value { let json = JSON(value) print(json.arrayValue[0]["uniqueUsers"].stringValue) } }更多推荐
Alamofire无法访问json响应的键
发布评论