2017-05-27 50 views
0

我試圖解析JSON文件。第一級工作正常,但是當我想深入一步時,它不再工作。解析NSArray的斯威夫特卡倫特3

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收到此錯誤:‘任何’ 「類型有沒有標會員」

打印(產品)的值如下:

enter image description here

我已經嘗試過在這裏提供了一些解決方案,但毫無效果。它可能是數組中的數據有問題嗎?

我會很樂意爲每一個想法,你可以提供幫助解決這一問題。

感謝, 亞歷山大。

+1

投你的產品[字符串:AnyObject]然後遍歷它不投關鍵「ASIN」設置爲[[字符串:AnyObject] – Raymond

+0

非常感謝 - 這工作了罰款! –

+2

不客氣。儘量避免使用NSDictionary和NSArray以及快速標準的代碼。 :-) https://engineering.vokal.io/iOS/CodingStandards/Swift.md.html https://github.com/raywenderlich/swift-style-guide – Raymond

回答

2

你需要做的是投你的陣列到[[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 
} 
+1

感謝您的解釋 - 我會記住這一點和更新我的代碼。 –