2017-05-27 16 views
0

JSONファイルを解析しようとしています。最初のレベルはうまくいきますが、私が一歩一歩深くしたいときは、それ以上は働きません。SwiftのNSArrayの解析3

私はこのようにそれをしようとすると、私はASINに値を割り当てることで、このエラーを取得
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]] 
     } 
    }) 
} 

: 『?どれ』 「タイプ何の添字メンバー」

印刷(製品)の値を持っていないと、次のようになります。

enter image description here

私はすでにここに提供されるいくつかのソリューションを試みたが、何も働きました。配列内のデータに問題はありますか?

この問題を解決するために提供できるすべてのアイデアに満足しています。

ありがとう、 アレクサンダー。

+1

がにあなたの製品をキャスト[[文字列:ANYOBJECT]]それを反復処理し、[:ANYOBJECT] [文字列]にキー「ASIN」をキャストしないでください – 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

あなたの説明をありがとう - 私はそれを念頭に置いて私のコードを更新してください。 –