Search code examples
swiftxcodensarray

Parsing NSArray in Swift 3


I am trying to parse a JSON file. The first level works fine, but when I want to get a step deeper, it doesn't work any more.

if let json = try JSONSerialization.jsonObject(with: ReceivedData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
    DispatchQueue.main.async(execute: {
        let tokensLeft = json["tokensLeft"]

        print("Tokens Left")
        print(tokensLeft)

        let product = json["products"]

        print(product)

        for i in 0 ..< (product as AnyObject).count {
            let asin = product[i]["asin"] as? [[String:AnyObject]]
        }
    })
}

When I try it like this, I get this error at assigning a value to asin: "Type 'Any?' has no subscript members"

The value of print(product) looks like this:

enter image description here

I already tried several solutions provided here, but nothing worked. Could it be a problem with the data in the array?

I would be happy for every idea you can provide to help solving this issue.

Thanks, Alexander.


Solution

  • What you need to do is to cast your array into an [[String:Any]]. Do it like this and check the comments for explanations:

    if let productsDictionary = json["products"] as? [[String:Any]] {
        // By doing if let you make sure you have a value when you reach this point
    
        // Now you can start iterate, but do it like this
        if let asin = productsDictionary["asin"] as? String, let author = productsDictionary["author"] as? String, etc... {
            // Use asin, autoher etc in here. You have now made sure that these has valid values
        }
    
        // If you have values that can be nil, just do it like this
        let buyBoxSellerIdHistory = productsDictionary["buyBoxSellerIdHistory"] as? Int
    }