Search code examples
iosjsonswiftalamofire

"Type 'Any' has no subscript members" error on Alamofire 4.0


I am using Alamofire 4.0 with Swift 3.0 and I am using the following code to parse the JSON:

Alamofire.request(url!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

    switch(response.result) {
        case .success(_):
            if let JSON = response.result.value{
                print(JSON)
                //print(JSON["name"])
                //print(JSON["age"])
            }
            break

        case .failure(_):
            print("There is an error")
            break
    }
}

And it gives me the following response:

(
    {
        Name = "Peter";
        Age = "18";
    }
)

The problem is that I could not access to that values (Name and Age) because when I try to do JSON["name"] I am getting the following error:

Type 'Any' has no subscript members

I also have tried adding as? [String: Any] as this question suggest: Alamofire fire variable type has no subscript members and this other one also suggest: Type Any has no subscript members Error in Swift 3.0? but any response is giving to me when I use it.

If I use:

case .success(_):
    if let JSON = response.result.value as? [String: Any]{
          print(JSON)
          print(JSON["TitularEmail"] as! String)
     }
     break

No errors are shown neither in Xcode or in the console of Xcode. Instead, no response is given.

How can I solve this error on a proper way? It is ok, with the solution before I am not getting any error but I am not getting any response also so it does not fix it at all.

Thanks in advance!


Solution

  • Try below code:

    Alamofire.request(url!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
    
    switch(response.result) {
        case .success(_):
            if let JSON = response.result.value as! [[String : Any]]!{
                    print("JSON: \(JSON)")
                    let dic = JSON[0] as [String:AnyObject]!
                    print("TitularEmail : ",dic?["TitularEmail"])
                }
            break
    
        case .failure(_):
            print("There is an error")
            break
    }
    }