在 Swift 3 中解析 NSArray

Parsing NSArray in Swift 3

我正在尝试解析 JSON 文件。第一关还行,想再深入一步就不行了

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]]
        }
    })
}

当我这样尝试时,我在为 asin 赋值时遇到此错误: "Type 'Any?' has no subscript members"

print(product) 的值如下所示:

我已经尝试了这里提供的几种解决方案,但没有任何效果。会不会是数组里面的数据有问题?

我很高兴你能提供任何想法来帮助解决这个问题。

谢谢, 亚历山大.

您需要做的是将数组转换为 [[String:Any]]。这样做 并查看注释以获取解释:

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
}