我正在开发一个项目,并且已经达到了我希望在表格视图中显示来自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)
提前感谢帮助!!!
答案 0 :(得分:0)
首先,不要在Swift中使用NSDictionary
和NSArray
,使用原生类型。
您正在将与数组相关的枚举API应用于字典。字典相关的API是
for (key, eachFetchedRestaurant) in fetchedData
您有两种选择:
fetchedData
确实应该是字典然后投出
let fetchedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
并使用上面提到的枚举API
(越有可能)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)