2017-03-05 97 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