【问题标题】:swift 4 Parse JSON without keys with Alamofireswift 4 使用 Alamofire 解析没有键的 JSON
【发布时间】:2018-06-13 10:42:50
【问题描述】:

伙计们,我想从 JSON 中获取所有名称(下面的屏幕截图)并将它们放到 tableView 中。问题是......我有这个代码的字典。现在,我如何获取每个名称值并将它们放在 tableView 上。

func getDataFromApi(){
    Alamofire.request("https://api.coinmarketcap.com/v2/listings/").responseJSON{ response in

        if let locationJSON = response.result.value{
            let locationObject: Dictionary = locationJSON as! Dictionary<String, Any>
            for (key, value) in locationObject {
                print("id:\(key), value:\(value)")
            }
        }
    }
}

【问题讨论】:

  • 你想要“数据”数组对吗?
  • @DilipTiwari 是的..
  • 你可以很容易地得到它......你想从“数据”数组中得到哪些值
  • @DilipTiwari 我想得到所有的名字......把它们放在 tableview 之后
  • 哦,我明白了,我会尝试等待

标签: json swift alamofire


【解决方案1】:

我建议将字典响应转换为 Currency 对象:

class Currency: NSObject {
    var id: Int!
    var name: String!
    var symbol: String!
    var websiteSlug: String!

    init(id: Int, name: String, symbol: String, websiteSlug: String) {
        super.init()

        self.id = id
        self.name = name
        self.symbol = symbol
        self.websiteSlug = websiteSlug
    }
}

然后在变量部分下定义currencies数组:

var currencies = [Currency]()

最后将 getDataFromApi 实现更改为:

func getDataFromApi() {
    Alamofire.request("https://api.coinmarketcap.com/v2/listings/").responseJSON{ response in
        if let locationJSON = response.result.value as? [String: Any] {
            let data = locationJSON["data"] as! [[String: Any]]
            for dataItem in data {
                let currency = Currency(id: dataItem["id"] as! Int,
                                        name: dataItem["name"] as! String,
                                        symbol: dataItem["symbol"] as! String,
                                        websiteSlug: dataItem["website_slug"] as! String)

                self.currencies.append(currency)
            }

            print(self.currencies)
        }
    }
}

我总是建议对对象的响应进行建模,因为它可以让您更好地管理需要在屏幕上显示的数据并保持代码结构井井有条。

现在您可以轻松地显示来自currencies 数组的UITableView 对象中的数据。

【讨论】:

    【解决方案2】:

    我建议将字典中的数组响应转换为货币对象:

     var dataArray = NSArray()
            @IBOutlet var tableView: UITableView!
            override func viewDidLoad() {
                super.viewDidLoad()
                // Do any additional setup after loading the view, typically from a 
            nib.
                self.getDataFromApi()
            }
    
            override func didReceiveMemoryWarning() {
                super.didReceiveMemoryWarning()
                // Dispose of any resources that can be recreated.
            }
            func getDataFromApi(){
                Alamofire.request("https://api.coinmarketcap.com/v2/listings/").responseJSON{ response in
    
                    if let locationJSON = response.result.value{
                        let locationObject: Dictionary = locationJSON as! Dictionary<String, Any>
                        self.dataArray = locationObject["data"]as! NSArray
                        self.tableView.reloadData()
    
        //                for (key, value) in locationObject {
        //                    print("id:\(key), value:\(value)")
        //                }
                    }
                }
            }
            func numberOfSections(in tableView: UITableView) -> Int {
                return 1
            }
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
               return dataArray.count
            }
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCell(withIdentifier:"cell") as! UITableViewCell
                cell.textLabel?.text = (dataArray.object(at:indexPath.row) as! NSDictionary).value(forKey:"name") as! String
                cell.detailTextLabel?.text = (dataArray.object(at:indexPath.row) as! NSDictionary).value(forKey:"symbol") as! String
                return cell
            }
    

    【讨论】:

      【解决方案3】:
      var nameArray = [String]()
      
      
      override func viewDidLoad() {
       super.viewDidLoad()
      
          getData()
       }
      
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      
        return nameArray.count
       }
      
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
      let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! tableCell
      cell.nameLabel.text = nameArray[indexPath.row]
      return cell
      
       }
      
      func alamofire() {
        Alamofire.request("https://api.coinmarketcap.com/v2/listings/", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
      
          switch(response.result) {
          case .success(_):
              guard let json = response.result.value as! [String:Any] else{ return}
              guard let data = ["data"] as! [[String: Any]] else { return}
      
              for item in data {
      
                  if let name = item["name"] as? String {
                      self.nameArray.append(name)
                  }
      
                  DispatchQueue.main.async {
                      self.tableView.reloadData()
                  }
              }
      
      
              break
      
          case .failure(_):
              print(response.result.error as Any)
              break
      
          }
      }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2019-08-05
        • 1970-01-01
        • 2018-09-05
        • 2020-11-19
        • 1970-01-01
        • 1970-01-01
        • 2020-02-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多