Swift 3 - 如何使用 Alamofire 和 SwiftyJSON 获取 JSON 对象
Swift 3 - How to get JSON Objects with Alamofire and SwiftyJSON
我想为我的 REST 使用 Alamofire 和 SwiftyJSON api.I 已经访问了根 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
}
你需要做的就是为上面提到的json创建一个模型,然后你就可以很容易地填充collectionview中的数据
你走在正确的轨道上。这是我通常的做法。
....
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 可以生成相当多的类型,本质上这是为您进行类型转换。
我想为我的 REST 使用 Alamofire 和 SwiftyJSON api.I 已经访问了根 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
}
你需要做的就是为上面提到的json创建一个模型,然后你就可以很容易地填充collectionview中的数据
你走在正确的轨道上。这是我通常的做法。
....
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 可以生成相当多的类型,本质上这是为您进行类型转换。