【问题标题】:Retrieve specific Array from JSON in swift in the form of Array of Keys and Values?以键和值数组的形式快速从 JSON 中检索特定数组?
【发布时间】:2016-08-11 18:37:49
【问题描述】:

JSON

{
   "11/08/22":[
    {
      "Bill Gates":"Microsoft",
      "Steve Balmer":"Microsoft"
    }],

   "13/08/22":[
    {
      "Tim Cook":"Apple",
      "Jony Ive":"Apple"
    }]

}

Swift 代码

let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
    do {
        if let jsonDate = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {


            print(jsonResult)

            //Get Result into Seperate Arrays
            let keys = jsonResult.flatMap(){ $0.0 as? String }
            let values = jsonResult.flatMap(){ $0.1 as? String }

        }
    } catch let error as NSError {
        print(error)
    }

})
jsonQuery.resume()

要求:

如果我从程序 “11/08/22” 传递,我应该能够以 Array of String 的形式获取所有键和值数组名为 "11/08/22"

更好的解释:

它应该进入 11/08/22,它应该检索“Bill Gates”、“Steve Balmer”作为键和“Microsoft”作为两个单独数组中的值

【问题讨论】:

  • 可以看到,您的 JSON 在键 "11/08/22" 中包含一个字典数组。您希望从哪里得到一个字符串数组?
  • 给定输入"11/08/22",您想要的字符串输出(确切地说)是什么样的?
  • 你试过jsonResult("11/08/22").flatMap(){ $0.0 as? String }吗?
  • 我想要像“比尔盖茨”“史蒂夫巴尔默”这样的名字数组和像“微软”这样的不同公司数组
  • @Santosh 不起作用非函数类型'NSDictionary'的调用值

标签: ios arrays json swift


【解决方案1】:

对于这个例子,让我们使用一个数组来收集人员和一个集合来收集公司:

var people: [String] = []
var companies: Set<String> = []

使用“11/08/22”键为 JSON 字典下标,并将结果转换为字典数组。

遍历该数组并在循环中,将键添加到人员数组并将值插入公司集中。

let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
    do {
        if let jsonDate = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {

            if let dateContent = jsonResult["11/08/22"] as? [[String:String]] {
                for group in dateContent {
                    people.appendContentsOf(group.keys)
                    group.values.forEach { companies.insert($0) }
                }
            }

        }
    } catch let error as NSError {
        print(error)
    }

})
jsonQuery.resume()

print(people)
print(companies)

结果:

[“史蒂夫·巴尔默”,“比尔·盖茨”]
[“微软”]

【讨论】:

    【解决方案2】:
    let keys=jsonResult["11/08/22"]?.allKeys as? [String];                       
    let values=jsonResult["11/08/22"]?.allValues as? [String];
    

    就这么简单

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 2019-08-25
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      相关资源
      最近更新 更多