markhorrocks markhorrocks - 1 month ago 18
JSON Question

How to parse this json with Alamofire 4 in Swift 3?

I have the json below but unable to figure out how to parse it in Swift 3. My code is below. The json from the API has an array root. I am using Xcode 8.2.1 with Swift 4 and Alamofire 4.0.

["items": <__NSArrayM 0x608000248af0>(
{
currency = USD;
image = "https://cdn.myDomain.com/image.jpg";
"item_title" = "Antique Table";
"name:" = "";
price = 675;
},
{
currency = USD;
image = "https://cdn.mydomain.com/image2.jpg";
"name:" = "";
price = 950;
...


Here is my code. I have tried to get an array r dictionary from the results but it's always nil.

Alamofire.request(myURL)
.responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
})
}

func parseData(JSONData: Data) {

do {
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.mutableContainers) as! [String: Any]
print(readableJSON)
}
catch {
print(error)
}
}


I have tried this
let item = readableJSON["items"] as? [[String: Any]]
as suggested here but it would not compile with an error
[String:Any] has no subscript
and
let item = readableJSON["items"] as? [String: Any]!
compiles with a warning
Expression implicitly coerced from string
but produces nil. Parsing this json is life or death for me.

Answer Source

This was the parse json function I eventually came up with. The problem for this json data is that it is a dictionary inside an array. I am a noob and most of the answers and how tos I saw would not fit my json data. Here is the function I finally came up with with worked.

var myItems = [[String:Any]]()

then in my view controller class

func loadMyItems() {

    Alamofire.request(myItemsURL)
        .responseJSON(completionHandler: {
            response in                
            self.parseData(JSONData: response.data!)

            self.collectionView.reloadData()                
        })
}

func parseData(JSONData: Data) {        
        do {                
            let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.allowFragments) as! [String: Any]

            let items = readableJSON["items"] as! [[String: Any]]

            self.myItems = items

 }               
        catch {
         print(error)
        }
}


func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as? myCell

    let dictionary = myItems[indexPath.row] as [String:Any]
    if let item_title = dictionary["item_title"] as? String {
        cell!.textLabel.text = item_title
        print(item_title)
    }

    return cell!
}