簡體   English   中英

swift 4解析JSON,無需使用Alamofire鍵

[英]swift 4 Parse JSON without keys with Alamofire

伙計們,我想從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)")
            }
        }
    }
}

在此輸入圖像描述

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

    }
}

}

我建議將字典響應轉換為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對象中的數據。

我建議轉換Array in dictionaries響應而不是Currency對象:

 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
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM