我无法从JSON API获取数据,它有点复杂和嵌套,我想从“能力”数组中获取“resource_uri”

时间:2018-03-06 13:38:11

标签: ios json swift

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()
    }
}

3 个答案:

答案 0 :(得分:0)

这是一个非常复杂的解析响应,pokeapi可以让您更轻松地深入了解所需的数据。

但是,这部分应该是一个数组:

if let name = actorArray.value(forKey: "abilities") as? NSDictionary

可能是这样的:

if let dict = actorArray.value(forKey: "abilities") as? [NSDictionary]

然后你需要遍历dict并获得类似于此的uri:

if let dict = actorArray.value(forKey: "abilities") as? NSDictionary {
    for dictionary in dict {
        if let uri = dict["resource_uri"] as? String {
            // Do something with uri here
        }
    }
}

答案 1 :(得分:0)

两种方式:

  1. 将您想要的网址(https://pokeapi.co/api/v1/pokemon/)过去到任何浏览器并复制并将您的输出(JSON)复制到Online JSON Editor并分析您可以转换为模型的内容,然后创建模型类(灵感来自JSON)并转换和映射。
  2. 快速解决方案:将结果(JSON)传递给Object Mapper Github,它最终会为您提供模型或模型数组。
  3. 希望这会有所帮助。 快乐的编码。

答案 2 :(得分:-1)

请使用以下代码获取资源URI和能力数组

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!)

                if let subDict = jsonDict?.value(forKey: "meta") as? NSDictionary {
                    if let name = subDict.value(forKey: "next") {
                        self.lableArray.append(name as! String)
                    }
                }
                if let objectsArray = jsonDict?.value(forKey: "objects") as? NSArray {
                    if let actorArray = (objectsArray.firstObject as? NSDictionary)?.value(forKey: "abilities") as? [NSDictionary]{
                        for dictionary in actorArray {
                            if let uri = dictionary["resource_uri"] as? String {
                                self.resource_uri.append(uri)
                            }
                        }
                    }
                }
            }

            OperationQueue.main.addOperation({
                print("resource uri \(self.resource_uri)")
                print("labelarray \(self.lableArray)")
            })

        }).resume()
    }