ios - Swift 3 - 如何使用 Alamofire 和 SwiftyJSON 获取 JSON 对象

标签 ios json swift alamofire swifty-json

我想为我的 REST api 使用 Alamofire 和 SwiftyJSON。我已经访问了根 json,但我无法访问 json 的对象。结合这两个库正确解析它的最佳方法是什么?

我的 JSON:-

[
{
    "ID": 2,
    "Nm": "ABC",
    "Descr": null,
    "BeenCnt": "9",
    "FavCnt": "9",
    "ImgPath": "pathtoimage",
    "TypeID": 4,
    "Type": null,
    "DayCnt": 5,
    "NightCnt": 4,
    "ValidDate": null,
    "UsrCommentCnt": null,
    "TourDates": null,
    "CityList": [
        {
            "KeyID": null,
            "ID": 1,
            "Data": "abc"
        },
        {
            "KeyID": null,
            "ID": 12,
            "Data": "abc"
        }
    ],
    "Seller": {
        "ID": 1,
        "Nm": "abc",
        "CityNm": null,
        "StateNm": null,
        "CommentCnt": null,
        "BeenCnt": null,
        "Add": null,
        "PackList": []
    },
    "Chrg": {
        "ID": 0,
        "PaxDetail": "Per Person",
        "PkgMode": null,
        "Amt": 15000,
        "AmtCurrID": 2,
        "AmtCurr": null,
        "ChargeSeq": 0
    },
    "ItineraryList": []
}

我希望“Chrg”填充到我的 UICollectionView 中。

我在编码方面的尝试:-

Alamofire.request(url).responseJSON { (responseData) -> Void in


        if((responseData.result.value) != nil) {
            let swiftyJSONVar = JSON(responseData.result.value!)

            if let resData = swiftyJSONVar[].arrayObject
            {
                self.arrRes = resData as! [[String:AnyObject]]
                print(self.arrRes)
            }

            if self.arrRes.count > 0 {
                self.collection.reloadData()
            }

        }
    }

我的UICollectionViewCell:-

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PackagesCell
    var dict = arrRes[(indexPath as NSIndexPath).row]
    var charge = dict["Chrg"] as! Dictionary<String,String>
    cell.amtLbl.text = charge["Amt"] as? String
    cell.NmLbl.text = dict["Nm"] as? String
    cell.nightsLbl.text = String(Int((dict["NightCnt"] as! Int64)))
    cell.dayLbl.text = String(Int(dict["DayCnt"] as! Int64))

    cell.perPersonLbl.text = dict["PaxDetail"] as? String
    cell.validTillLbl.text = dict["ValidDate"] as? String
    cell.iternaryListLbl.text = dict["CityList"]?["Data"] as? String
    cell.cmtLbl.text = dict["BeenCnt"] as? String
    cell.beenCmtLbl.text = dict["FavCnt"] as? String
    self.id = String(dict["ID"] as! Int64)
    let ImgPath = dict["ImgPath"] as? String
    let fulURL = "\(self.site + ImgPath!)"
    let newURL = fulURL.replacingOccurrences(of: "\\", with: "/")
    let newwURL = newURL.replacingOccurrences(of: "png", with: "jpg")
    cell.img.sd_setImage(with: URL(string:newwURL),  placeholderImage: UIImage(named: "placeholder.png"))
    return cell
}

最佳答案

我认为有更好的方法来解析 JSON

只需对其进行类型转换:

if let jsonArray = responseData.result.value as? Array<Dictionary<String,Any>> {
     print("Json Response: \(jsonArray)") // serialized json response
     self.arrRes = jsonArray
}
if let arrCityList = self.arrRes[0]["CityList"] as? Array<Dictionary<String,Any>> {
     print(arrCityList)// You can populate the table from city list
}

关于ios - Swift 3 - 如何使用 Alamofire 和 SwiftyJSON 获取 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46314640/

相关文章:

ios - 是否可以为 iphone 制作一个 "Ignore No More"应用程序

json - 如何在 Azure 策略中强制实现标签值模式?

ios - 如果方向改变,如何设置框架?

ios - Invalid Bundle - dylib 搜索路径中不存在您的应用程序引用的一个或多个动态库 | Xcode 13.3

javascript - angular.fromJson(data.Body) 与 JSON.parse(data.Body)

swift - NSURLSession 响应字符串完成 block - Swift

ios - 图像是由 UIImagePickerControllerSourceTypeCamera 拍摄的如何将其保存在 ios 的数据库中

ios - Xcode:应用程序构建,但同时构建 "runs"和 "finishes"

ios - 连接到 iOS 的蓝牙外设在后台不工作

c# - ScriptIgnore 元数据