Matt Matt - 1 year ago 51
JSON Question

Get all items in JSON and put them in an array

I am using Alamofire to get some JSON data and rather than having everything hardcoded, I was wondering how to simply include everything in the array.

Currently, this is the JSON file:


My swift code:

var pickerData: [String] = [String]() //Array of content.
override func viewDidLoad() {

Alamofire.request(.GET, "").responseJSON{ (response) -> Void in

if let JSON = response.result.value{
let One = JSON["One"] as! String
let Two = JSON["Two"] as! String
let Three = JSON["Three"] as! String
let Four = JSON["Four"] as! String
let Five = JSON["Five"] as! String
self.mypickerview.delegate = self
self.mypickerview.dataSource = self
self.pickerData = [One, Two, Three, Four, Five]

How can I not make them hardcoded so that I can have my file like this and it would still work and include everything in the JSON, even if I add more in the future:


Answer Source

Aaron is right, your JSON should use an array to hold the item values.

But if you're stuck with this format, you can get the values in your pickerData like this:

if let JSON = response.result.value as? [String:AnyObject] {
    let result = JSON.values.flatMap({ String($0) })

pickerData is now:

["Item1", "Item2", "Item3", "Item4", "Item5"]

and items will be sorted in the picker array even if you add new ones later.