2016-09-23 92 views
0

我使用Alamofire 4.0Swift 3.0,我使用下面的代码来解析JSON“类型‘任何’有没有下成员”错误的Alamofire 4.0

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

,这让我以下回应:

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

的问题是,我无法访问该值(NameAge),因为当我尝试做JSON["name"]我收到以下错误:

Type 'Any' has no subscript members

我也尝试添加as? [String: Any]因为这个问题建议:Alamofire fire variable type has no subscript members,这等一个也提示:Type Any has no subscript members Error in Swift 3.0?但任何反应是给我,当我使用它。

如果我使用:显示无论是在Xcode或在Xcode的控制台

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

没有错误。相反,没有给出答复。

如何以正确的方式解决此错误?没关系,在我没有得到任何错误之前解决方案,但我没有得到任何回应,所以它根本没有修复它。

在此先感谢!

+1

你JSON是似乎砥数组,没有字典。那么试试? [[String:Any]]不是? [String:Any] – larva

回答

2

试试下面的代码:

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 
} 
} 
+0

感谢您的回复,但它给了我同样的行为。在控制台上没有错误和没有响应。 –

+0

你能打印JSON吗? –

+0

不,当我尝试投射它时,我无法打印JSON。当我不施放它时,我可以完美地打印它。 –

相关问题