从'(key:Any,value:Any)'转换为不相关的类型'[String:Any]'总是失败

时间:2018-05-14 09:32:10

标签: json swift3

我正在开发一个项目,并且已经达到了我希望在表格视图中显示来自Web服务的数据的阶段。我的json数据是字典格式的,我正在循环使用密钥从字典中获取数据,但它正在收到警告。所以,请帮我解决这种警告。

我的循环是: -

<Button BorderRadius="15" Text="Click"/>

在此行上收到警告: -

让eachRestaurant = eachFetchedRestaurant为! [String:Any]

let fetchedData = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary

 for eachFetchedRestaurant in fetchedData {

     let eachRestaurant = eachFetchedRestaurant as! [String : Any]
     let restaurantName = eachRestaurant["restName"] as! String
     let restaurantImage = eachRestaurant["restaurant_image"] as! String

     self.fetchedRestaurant.append(Restaurants(restaurantName: restaurantName, restaurantImage: restaurantImage))
     }
     print(self.fetchedRestaurant)

提前感谢帮助!!!

2 个答案:

答案 0 :(得分:0)

首先,不要在Swift中使用NSDictionaryNSArray,使用原生类型。

您正在将与数组相关的枚举API应用于字典。字典相关的API是

for (key, eachFetchedRestaurant) in fetchedData

您有两种选择:

  1. fetchedData确实应该是字典然后投出

    let fetchedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
    

    并使用上面提到的枚举API

  2. (越有可能)fetchedData应该是数组,那么你必须投出

    let fetchedData = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]
    

答案 1 :(得分:0)

由于JSON响应是(key, value)格式的数组,因此您的获取数据应为[[String:Any]]格式。这是更新的代码。

let fetchedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [[String:Any]]

 for (key,eachFetchedRestaurant) in fetchedData {

     let eachRestaurant = eachFetchedRestaurant as! [String : String]
     let restaurantName = eachRestaurant["restName"] as! String
     let restaurantImage = eachRestaurant["restaurant_image"] as! String

     self.fetchedRestaurant.append(Restaurants(restaurantName: restaurantName, restaurantImage: restaurantImage))
  }
  print(self.fetchedRestaurant)