数据不解析我想将数据解析为字典然后解析为数组,然后迭代它

问题描述 投票:0回答:4

数据未解析我想将数据解析为字典然后解析为数组,然后迭代它并将其保存到自定义数组。来自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")
ios swift alamofire swifty-json
4个回答
0
投票

如果让dict =响应为,请替换? NSDictionary如果让dict = response.result.value为? NSDictionary并检查


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"]

            }

0
投票
if let dict = response  as? [String,Any]{
    if let stores = dict["stores"] as? [[String:Any]]{
        for items in stores{
            //Do stuff here
        }
    }
}

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")
© www.soinside.com 2019 - 2024. All rights reserved.