繁体   English   中英

如何在快速3中获得给定Json响应的计数?

[英]how to get the count for the given Json response in swift 3?

在api中,我获取以下数据,在此我需要获取所有数组中的总名称数

{
  "Flat": [
    {
      "price": "$5.00", 
      "id": 11, 
      "name": "Fixed"
    }
  ], 
  "United Parcel Service": [
    {
      "price": "$109.12", 
      "id": 1, 
      "name": "worldwide Expedited"
    }, 
    {
      "price": "$120.18", 
      "id": 2, 
      "name": "worldwide Express saver"
    }
  ]
}

我试过下面的代码来获取所有数组中的名称计数

    var arrayss =  [String:AnyObject]()
    var keys = [String]()
    let urlString = "http://www.json-generator.com/api/json/get/bVgbyVQGmq?indent=2"
    var totalCount = 0
func shippingmethodURL() {
        let url = NSURL(string: self.urlString)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                self.arrayss = jsonObj as! [String : AnyObject]
                self.keys = jsonObj?.allKeys as! [String]
                OperationQueue.main.addOperation({
                    self.shippingTableView.reloadData()
                    let sectionHeight = self.arrayss.count * 31
                    let cellHeight = self.keys.count * 44
                    self.shippingHeightConstraint.constant = CGFloat(sectionHeight + cellHeight)
                    self.heightConstant = Int(self.shippingHeightConstraint.constant)
                    self.delegate?.heightConstant(int: self.heightConstant!)
                })
            }
        }).resume()
    }

首先,当它们具有本机Swift等效项(例如NSURLNSDictionary )时,不要使用Foundation数据类型。

除此之外,您的问题是您正在计算字典的键。 但是,您要做的是遍历字典,使用条件转换检查与该键关联的值是否为数组,如果为数组,请检查该数组的字典元素是否具有“名称”键,如果这样做,则增加计数,否则不执行任何操作。

另外,在解析JSON数据时也不要使用强制展开和强制转换,因为在网络响应中,它们很有可能会失败并且您的应用会崩溃。

func shippingmethodURL() {
    guard let url = URL(string: self.urlString) else {return}
    URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) -> Void in
        if let data = data, let jsonObj = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [String:AnyObject] {
            self.arrayss = jsonObj
            self.keys = Array(jsonObj.keys)

            var totalCount = 0
            for value in jsonObj.values {
                if let array = value as? [[String:Any]] {
                    for element in array {
                        if let name = element["name"] as? String {
                            totalCount += 1
                        }
                    }
                }
            }
            //update UI and other variables here
        }
    }).resume()
}

正如在其他答案中所建议的那样,除了前缀NS (即NSDictionaryNSURL )之外,您应该始终考虑本机Swift类型。 因此,您应该将本机Swift类型用作DictionaryURL 而另一件事是它更好地使用Any其他比AnyObject 您可以在这里看看为什么我这么说。

说的足够多,您应该看一下:

var arrayss = [String:Any]()
var keys = [String]()
let urlString = "http://www.json-generator.com/api/json/get/bVgbyVQGmq?indent=2"
var nameKeyCount = 0

func shippingmethodURL() {
    guard let url = URL(string: self.urlString) else {return}
    URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) -> Void in
        if let data = data, let jsonObj = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [String:Any] {
            self.arrayss = jsonObj
            self.keys = Array(jsonObj.keys)
            // Now you want to know the count for `name` key
            // Below is the standard way in swift.
            // Looping through each of the object is cumbersome
            self.nameKeyCount = jsonObj.flatMap { $0.value.flatMap { $0.filter { $0.key == "name" } } }.count

            // As URLSession's data task is an asynchronous task and done in a thread other than main thread, you should have your main thread to update any UI related thing
            Dispatch.main.async {
                // update UI here
            }
        }
    }).resume()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM