数据未解析我想将数据解析为字典然后解析为数组,然后迭代它并将其保存到自定义数组。来自JSON结构化的{"stores" : [{},{}]}
码:
Alamofire.request(NEARBY_STORES, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON{ (response) in
if response.result.error == nil {
print(response)
if let dict = response as? NSDictionary
{ print("dict saved")
if let stores = dict["stores"] as? Array<AnyObject>
{
for items in stores
{
let storeName = items["name"] as? String
let storeCover = items["cover"] as? String
let minimumOrder = items["min_order_amt"] as? String
let storeRating = items["average_rating"] as? String
let storeSpeed = items["delievery_time"] as? String
let storeLogo = items["logo"] as? String
let shoplist = shopModel(shopName: storeName!, shopBGImage: storeCover!, shoplogo: storeLogo!, speed: storeSpeed!, accuracy: storeRating!, minimumOrder: minimumOrder!)
self.shopLists.append(shoplist)
print("PARSED")
如果让dict =响应为,请替换? NSDictionary如果让dict = response.result.value为? NSDictionary并检查
我通常使用SwiftyJSON来做这个解析。
if let result = response.result.value {
let dict = JSON(result)
print(dict)
//you can try to print your stores and continue with your logic
let stores = dict["stores"]
}
if let dict = response as? [String,Any]{
if let stores = dict["stores"] as? [[String:Any]]{
for items in stores{
//Do stuff here
}
}
}
试试这个:
Alamofire.request(NEARBY_STORES, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON{ (response) in
if response.result.error == nil {
print(response)
if let dict = response as? Dictionary<String, Any> ?? [:]
{ print("dict saved")
if let stores = dict["stores"] as? Array ?? []
{
for items in stores
{
let itemDict = items as? Dictionary<String, Any> ?? [:]
let storeName = itemDict["name"] as? String
let storeCover = itemDict["cover"] as? String
let minimumOrder = itemDict["min_order_amt"] as? String
let storeRating = itemDict["average_rating"] as? String
let storeSpeed = itemDict["delievery_time"] as? String
let storeLogo = itemDict["logo"] as? String
let shoplist = shopModel(shopName: storeName!, shopBGImage: storeCover!, shoplogo: storeLogo!, speed: storeSpeed!, accuracy: storeRating!, minimumOrder: minimumOrder!)
self.shopLists.append(shoplist)
print("PARSED")