【问题标题】:Swift 3 - How to get JSON Objects with Alamofire and SwiftyJSONSwift 3 - 如何使用 Alamofire 和 SwiftyJSON 获取 JSON 对象
【发布时间】:2018-03-01 01:51:12
【问题描述】:

我想为我的 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": []
}

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

我在编码方面的尝试:-

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
}

【问题讨论】:

    标签: ios json swift alamofire swifty-json


    【解决方案1】:

    我认为解析 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
    }
    

    【讨论】:

    • UICollectionView中使用它?
    • 我想用'Chrg'填充UICollectionView项目你能帮我吗?
    • 它打印你的 json print("Json Response: \(jsonArray)") ?
    • 现在你在 jsonArray 中有你的 JSON 和 swift Array 集合,你可以在使用时使用它。
    • cell.amtLbl.text = dict["Amt"] as? String 无法获取价值
    【解决方案2】:

    你需要做的是为上面提到的json创建一个模型,然后你在collectionview中填充数据变得很容易

    【讨论】:

      【解决方案3】:

      你在正确的轨道上。这是我通常的做法。

      ....
      let jsonResponse = JSON(responseData.result.value!)
      var firstName = (jsonResponse["result"]["name"]).string?;
      var lastName = (jsonResponse["result"]["surname"]).string?;
      var emails = (jsonResponse["result"]["emails"]).array?;
      
      //make your object or object array here using the values above. e.g
      var cic = CustomItemForCollection( name : firstName , surname: lastName, emailArr: emails )
      ...
      

      SwiftyJson 中的 JSON 可以生成很多类型,本质上它的作用是为您进行类型转换。

      【讨论】:

        猜你喜欢
        • 2014-12-27
        • 2018-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-12
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        相关资源
        最近更新 更多