【问题标题】:Loop through Alamofire JSON Results in Swift在 Swift 中循环遍历 Alamofire JSON 结果
【发布时间】:2017-03-05 03:55:33
【问题描述】:

我有一个 Web 服务,它返回以下关于移动设备的 JSON 结果:

{
  "devices": {
    "device": [
      {
        "model": "iPhone 6",
        "OS": "iOS 10"
      },
      {
        "model": "iPad Air",
        "OS": "iOS 9"
      }
    ]
  }
}

我正在尝试遍历这个 JSON 的结果,结果应该是这样的:

[iPhone 6, iPad Air]
[iOS 10, iOS 9]

到目前为止,我想出的只是:

    for (_,_):(String, JSON) in json["devices"]["device"] {

 }

这将遍历“设备”数组,但我不确定如何查看字典并获取“模型”值,然后获取“操作系统”值。

更新:修改后的问题更清楚地说明了我的目标和我目前的目标。

【问题讨论】:

  • 向我们展示如何将数据保存在数组中。
  • 我有: var deviceArray: [AnyObject] = [] 然后添加到它会是这样的: deviceArray.append(test)

标签: ios swift loops alamofire swifty-json


【解决方案1】:

我将您的数据建模为字典,这似乎对我有用:

let dictionary = [
    "devices": [
        "device": [
            ["model": "ip6", "OS": "iOS10"],
            ["model": "ipad air", "OS": "iOS9"],
        ]
    ]
]
if let devices = dictionary["devices"], let deviceArray = devices["device"]  {
    for device in deviceArray {
        if let model = device["model"], let os = device["OS"] {
            print("\(model), \(os)")
            // Save your model and os to their respective arrays here
        }
    }
}

编辑:如果值来自 Alamofire 并假设返回有效,那么您只需将返回值存储到字典中并从上面执行相同的操作:

guard let dictionary = response.result.value as? [String: Any] else {
    print("Return result not in form [String: Any]")
    return
}

【讨论】:

  • 这会将值硬编码到字典中。我需要它是动态的,因为 JSON 可以返回 3 个设备或 40 个设备。
猜你喜欢
  • 1970-01-01
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 2019-02-18
相关资源
最近更新 更多