【发布时间】:2018-03-06 13:38:10
【问题描述】:
class ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {
//I got stuck in fetching data from JSON API, its little bit complex and //nested, anyone plz help me, I want to Get "resource_uri" from "abilities" //Array
@IBOutlet weak var tblData: UITableView!
final let urlString = "[https://pokeapi.co/api/v1/pokemon/][1]"
var lableArray = [String]()
var resource_uri = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lableArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let ceL = tableView.dequeueReusableCell(withIdentifier: "CeL") as! Celll
ceL.lbl.text = lableArray[indexPath.row]
return ceL
}
override func viewDidLoad() {
super.viewDidLoad()
downloadJsonWithURL()
}
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonDict = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
//print(jsonDict!)
for _ in jsonDict!{
if let subDict = jsonDict?.value(forKey: "meta") as? NSDictionary {
if let name = subDict.value(forKey: "next") {
self.lableArray.append(name as! String)
//print(self.lableArray)
}
if let actorArray = subDict.value(forKey: "objects") as? NSArray {
if let name = actorArray.value(forKey: "abilities") as? NSDictionary {
if let name = name.value(forKey: "resource_uri") as? NSArray
{
self.resource_uri.append(name as! String)
print(self.resource_uri)
}
}
}
}
}
}
OperationQueue.main.addOperation({
self.tblData.reloadData()
})
}).resume()
}
}
【问题讨论】:
-
你的 json 是什么?在这里打印。
-
请给我们看一个 JSON 样本。
-
为什么urlString有[1]应该是
final let urlString = "https://pokeapi.co/api/v1/pokemon/" -
也可以使用这个资源:json.parser.online.fr它将帮助你理解你的json的整个结构。