Alamofire can't access keys of json response

匿名 (未验证) 提交于 2019-12-03 02:42:02

问题:

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("http://codewithchris.com/code/afsample.json").responseJSON { response in     if let JSON = response.result.value {         print(JSON)     } } 

The issue is that when I run this:

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

I get the error:

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"] as String)

and

print(JSON["firstkey"] as [String:Any]

but they still give the same error.

This is the JSON on my endpoint:

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

回答1:

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("http://codewithchris.com/code/afsample.json").responseJSON { response in     if let JSON = response.result.value {         let json = JSON as! [String: Any]         print(json["firstkey"])     } } 

Edit 1: As you said in comments that you are using SwiftyJSON package. Sample code is as follows:

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


回答2:

You are trying to get the value with getting the object, try this:

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

Hope it will work!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!