【问题标题】:I got stuck in fetching data from JSON API, it's little bit complex and nested, I want to Get "resource_uri" from "abilities" Array我被困在从 JSON API 获取数据中,它有点复杂和嵌套,我想从“abilities”数组中获取“resource_uri”
【发布时间】: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的整个结构。

标签: ios json swift


【解决方案1】:

这是一个相当复杂的解析响应,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
        }
    }
}

【讨论】:

    【解决方案2】:

    两种方式:

    1. 将您想要的 URL(https://pokeapi.co/api/v1/pokemon/) 粘贴到任何浏览器并将输出 (JSON) 复制并粘贴到 Online JSON Editor 并分析可以转换为模型的内容,然后创建模型类(受 JSON 启发)并转换和映射.
    2. 快速解决方案:将您的结果 (JSON) 传递给 Object Mapper Github,它最终会为您提供模型或模型数组。

    希望这会有所帮助。 编码愉快。

    【讨论】:

      【解决方案3】:

      请使用以下代码获取资源 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()
          }
      

      【讨论】:

      • 我不知道兄弟为什么... :(
      • 我不是在问你兄弟@AbdulJabbar
      • 兄弟我还有个问题,可以讨论一下吗?
      • 请继续
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2020-01-26
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      相关资源
      最近更新 更多