Alamofire can't access keys of json response

前端 未结 3 2032
孤街浪徒
孤街浪徒 2021-01-26 05:20

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(         


        
3条回答
  •  粉色の甜心
    2021-01-26 06:06

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

提交回复
热议问题