swift 4解析JSON,无需使用Alamofire键

时间:2018-06-13 10:42:51

标签: json swift 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)")
            }
        }
    }
}

enter image description here

3 个答案:

答案 0 :(得分:2)

我建议将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
        }

答案 1 :(得分:1)

true

答案 2 :(得分: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)
        }
    }
}

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

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