我最近从 Objective-C 更新到 Swift,在以本机方式解析 JSON 时真的很混乱,所以在搜索 Stack Overflow 时,我发现了 SwiftyJSON API,它真的很酷。将解析的 JSON 值分配给标签时出现错误。我已经将结果存储在一个数组中,但是在tableview上显示它时,它显示了一个错误。
//Array where I store the parsed JSON
var categoryCount = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
getData()
}
func getData() {
Alamofire.request(.GET, "http://www.artively.com/api/MobileApi/get_parent_category")
.responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
self.parseJSON(json)
}
}
}
func parseJSON(json: JSON) {
for result in json["data"].arrayValue {
print("The count are",result["product_count"].int!)
self.categoryCount.append(result["product_count"].int!)
}
print("The category count are", categoryCount.count)
}
最后,当我执行此代码时,应用程序崩溃:
cell.countLable.text = "(categoryCount[indexPath.row])"
//Error appear in above code
这是 JSON 结果:
{
"responsecode": "200",
"responsemsg": "Successfull",
"data": [
{
"pk_category_id": 60,
"category_name": "Collage",
"category_logo": "http://www.artively.com//Upload/category_logo/28102015163738_collage_icon.png",
"category_logo_selected": "http://www.artively.com//Upload/category_logo/28102015163738_collage_icon.png",
"product_count": 10
},
{
"pk_category_id": 65,
"category_name": "Contemporary",
"category_logo": "http://www.artively.com//Upload/category_logo/28102015163521_contempory_icon.png",
"category_logo_selected": "http://www.artively.com//Upload/category_logo/28102015163521_contempory_icon.png",
"product_count": 242
},
...So on
在上面的响应中,我已经解析了"product_count"的值,将其存储在数组中并将其显示在表视图单元格上,但应用程序崩溃了......
解析后,您应该调用self.tableView.reloadData()
。然后还要确保要实现此方法:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.categoryCount.count
}
这将确保数组中的行数仅与数组中的元素一样多,因此indexPath.row
不会超过数组边界。