数据未解析我想将数据解析为字典,然后解析为数组,然后对其进行迭代并将其保存到自定义数组。来自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")
答案 0 :(得分:0)
替换是否让dict = response as? NSDictionary与if dict = response.result.value一样? NSDictionary和检查
答案 1 :(得分:0)
我通常使用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"]
}
答案 2 :(得分:0)
if let dict = response as? [String,Any]{
if let stores = dict["stores"] as? [[String:Any]]{
for items in stores{
//Do stuff here
}
}
}
答案 3 :(得分:0)
尝试一下:
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")