1

I'm really confused about parsing JSON data in Swift 3. This is a lot harder than I ever expected coming from a Javascript background.

Response from API:

[
{
    "ID": 1881,
    "image": "myimageURL",
},
{
    "ID": 6333,
    "image": "myimageURL",
}
]

My Swift code:

    let images = [] as Array

override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request(URL(string: "myURL")!,
        method: .get)
        .responseJSON(completionHandler: {(response) -> Void in
            print(response)
           //Parse this response. Then loop over and push value of key "image" of each object into the images array above.
    })
}

In Javascript I'd simply do

let images = []
let parsed = JSON.parse(response)
for(var i in parsed){
    images.push(parsed[i].image)
}
Thomas Charlesworth
  • 1,789
  • 5
  • 28
  • 53

2 Answers2

3
var images: [String] = []

Alamofire.request("https://apiserver.com/api/images") //replace url with your url
            .responseJSON { response in
                if let jsonArray = response.result.value as? [[String: Any]] {
                    print("JSON: \(json)") // serialized json response
                    for json in jsonArray {
                        let image = json["image"]
                        images.append(image)
                    }
                }
           }
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
0
let images = [] as NSArray

above line works fine but for better approach you can make it generic array of strings replace above line with

var images = [String]()

and insert below code to parse JSON object

switch(response.result) {
case .success(_):

if response.result.value != nil
{
    let array = response.result.value as! [[String: String]]
    array.forEach{ dictionary in
        images.append(dictionary["image"] ?? "")
    }
}

case .failure(_):
break
}
tailor
  • 680
  • 4
  • 12