我有一个像这样的json:
{"page":1,"totalPage":1,"listContent":[{"bizID":3,"bizName":"SHELL KEMANGGISAN","bizImage":"http//:www.goog@gmail.com","address":"JL KEMANGGISAN UTAMA, JAKARTA, 11480, INDONESIA","ratingAvg":1.0,"distance":14003691},{"bizID":4,"bizName":"SHELL DAAN MOGOT","bizImage":"http//:www.goog@gmail.com","address":"JL DAAN MOGOT KM 11, JAKARTA, 11710","ratingAvg":3.0,"distance":14004238}]}
我试着抓住这样的结果但错误:
do {
let jsonArr = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSArray
print("jsonArr:\(jsonArr)")
for json in jsonArr {
if let results = json["listContent"] as? NSArray {
for result in results {
let person = Bizz()
person.bizID = result["bizID"] as! String
person.bizName = result["bizName"] as! String
person.bizImage = result["bizImage"] as! String
person.address = result["address"] as! String
person.ratingAvg = result["ratingAvg"] as! String
self.businessBizz.append(person)
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
} catch {
print("Failed to get Content List: \(error)")
}
错误是:
无法将'__ NSCFString'(0x10756f2c8)类型的值转换为'NSArray'(0x10756fb88)。
此行的错误:
let jsonArr = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSArray
如何修复?并获取listcontent值。
答案 0 :(得分:2)
您的JSON是3.14159265359.toFixed(4)
> "3.1415"
表示字典不是数组..
[String: AnyObject]
您还应该将let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
if let results = json["listContent"] as? [[String: AnyObject]] {
for result in results {
let person = Bizz()
person.bizID = result["bizID"] as! Int
person.bizName = result["bizName"] as! String
person.bizImage = result["bizImage"] as! String
person.address = result["address"] as! String
person.ratingAvg = result["ratingAvg"] as! Float
self.businessBizz.append(person)
}
}
和result["ratingAvg"]
分别转换为Int和Float,因为它们在被解析时会转换为NSNumber。
您可以从here下载游乐场并自行测试。