使用 Alamofire 和 SwiftyJSON 难以解析 JSON
Difficulty parsing JSON with Alamofire and SwiftyJSON
我写了下面的代码:
Alamofire.request("\(NSLocalizedString("base_url", comment: ""))\(NSLocalizedString("url_rateCard", comment: ""))").responseJSON{response in
let status:Int = (response.response?.statusCode)!
switch status{
case 200:
switch response.result{
case .success(let suc):
let json = JSON(suc)
print(json)
self.rateCardCollectionView.delegate = self
self.rateCardCollectionView.dataSource = self
break
case .failure(let error):
print(error)
break
}
break
default:
print("Could not call ratecard api")
break
}
}
我得到了这个结果:
{
"error" : null,
"data" : [
{
"name" : "Air Conditioner 1.5ton",
"unit" : "piece",
"_id" : "58d3c7a277d862536fb5ec2e",
"itemComment" : "Mentioned price is subjected to change on vendor visit.",
"price" : 1450,
"icon" : "\/images\/rate-card\/undefined-1490685861277.png"
},
...
请查看 json,特别是图标字段。它应该是这样的:
"icon": "/images/rate-card/undefined-1490685861277.png",
该字符串在键数组的第一个字典中 data
:
let json = JSON(suc)
if let icon = json["data"][0]["icon"].string {
print(icon)
}
或者如果你想打印数组中的所有 icon
s
let json = JSON(suc)
if let data = json["data"].array {
for item in data {
if let icon = item["icon"].string {
print(icon)
}
}
}
我写了下面的代码:
Alamofire.request("\(NSLocalizedString("base_url", comment: ""))\(NSLocalizedString("url_rateCard", comment: ""))").responseJSON{response in
let status:Int = (response.response?.statusCode)!
switch status{
case 200:
switch response.result{
case .success(let suc):
let json = JSON(suc)
print(json)
self.rateCardCollectionView.delegate = self
self.rateCardCollectionView.dataSource = self
break
case .failure(let error):
print(error)
break
}
break
default:
print("Could not call ratecard api")
break
}
}
我得到了这个结果:
{
"error" : null,
"data" : [
{
"name" : "Air Conditioner 1.5ton",
"unit" : "piece",
"_id" : "58d3c7a277d862536fb5ec2e",
"itemComment" : "Mentioned price is subjected to change on vendor visit.",
"price" : 1450,
"icon" : "\/images\/rate-card\/undefined-1490685861277.png"
},
...
请查看 json,特别是图标字段。它应该是这样的:
"icon": "/images/rate-card/undefined-1490685861277.png",
该字符串在键数组的第一个字典中 data
:
let json = JSON(suc)
if let icon = json["data"][0]["icon"].string {
print(icon)
}
或者如果你想打印数组中的所有 icon
s
let json = JSON(suc)
if let data = json["data"].array {
for item in data {
if let icon = item["icon"].string {
print(icon)
}
}
}