2017-03-05 95 views
0

我有一个返回有关移动设备上的以下JSON结果的Web服务:遍历Alamofire 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"] { 

} 

这将循环ŧ通过“devices”数组,但我不知道如何查看字典并获取“模型”值,然后获取“os”值。

更新:修改后的问题更加清晰,以我的目标以及迄今为止的内容。

+0

向我们展示你如何保存在数组中的数据。 –

+0

我有:var deviceArray:[AnyObject] = [] 然后添加到它会像这样:deviceArray.append(test) – Martheli

回答

0

我模仿你的数据字典,这似乎为我工作:

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 
} 
+0

这将硬编码到字典中的值。我需要它是动态的,因为JSON可以返回3个设备或40个设备。 – Martheli

+0

查看我的更新回答 – Simon

+0

查看我上面更新的问题。 – Martheli